Automatic and Manual Dark Mode Toggle
Build a theme toggle that respects system preference by default and lets users override it manually.
Automatic and Manual Dark Mode Toggle is a free CSS Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the CSS Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Goal
An ideal dark mode implementation: auto-detects the OS preference by default, and provides a toggle button that lets users override it independently, with the preference persisted across page loads.
Architecture Overview
Three states to handle:
- System preference: use
prefers-color-schemewith CSS variables - User override: dark: set a class or data attribute on
<html> - User override: light: set a different class to prevent auto dark
CSS Token Setup
Define CSS variables that cascade correctly for all states:
:root { /* light defaults */
--bg: #ffffff; --text: #111;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #111; --text: #eee;
}
}
[data-theme="dark"] {
--bg: #111; --text: #eee;
}
[data-theme="light"] {
--bg: #ffffff; --text: #111;
}JavaScript Toggle Logic
Read saved preference, apply it, and update on toggle:
// On page load
const saved = localStorage.getItem('theme');
if (saved) document.documentElement.dataset.theme = saved;
// Toggle button
function toggleTheme() {
const current = document.documentElement.dataset.theme;
const system = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
if (!current) {
// No override yet; set opposite of system
const next = system === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = next;
localStorage.setItem('theme', next);
} else {
// Remove override (back to system)
delete document.documentElement.dataset.theme;
localStorage.removeItem('theme');
}
}Three-State Toggle
A more refined three-state toggle: Light | System | Dark:
const states = ['light', 'system', 'dark'];
let current = localStorage.getItem('theme') || 'system';
function cycle() {
current = states[(states.indexOf(current) + 1) % states.length];
if (current === 'system') {
delete document.documentElement.dataset.theme;
localStorage.removeItem('theme');
} else {
document.documentElement.dataset.theme = current;
localStorage.setItem('theme', current);
}
}Preventing Flash of Wrong Theme
Apply the saved theme synchronously before the page renders:
<!-- In <head>, before any styles -->
<script>
const t = localStorage.getItem("theme");
if (t) document.documentElement.dataset.theme = t;
</script>Toggle Button Accessibility
The toggle button should communicate the current state to screen readers. Update the accessible label when toggled:
<button id="theme-toggle" aria-label="Switch to dark mode">
🌙
</button>Animated Theme Transition
Smooth color transitions when the theme changes:
.theme-transitioning * {
transition: background-color 200ms ease, color 200ms ease !important;
}
// Add class, toggle, remove class after transitionSystem Change Listening
Also react if the user changes their OS preference while the page is open:
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', () => {
if (!localStorage.getItem('theme')) {
// No user override: let CSS media query handle it
// Just refresh the UI if needed
}
});Dark Mode Icons
Swap icons for each mode. Use the picture element for theme-aware images, or CSS to show/hide different icons:
.icon-sun { display: none; }
.icon-moon { display: block; }
[data-theme="dark"] .icon-sun { display: block; }
[data-theme="dark"] .icon-moon { display: none; }Summary: Implementation Checklist
Dark mode checklist:
- CSS variables for all color tokens
- prefers-color-scheme media query for auto detection
- data-theme attribute for manual override
- localStorage for persistence
- Inline script in head to prevent flash
- Accessible toggle button with dynamic aria-label
Quick Check
What technique prevents a "flash of wrong theme" when the page loads?
Recap
A complete dark mode toggle uses CSS variables for theme tokens, a prefers-color-scheme query for automatic detection, a data-theme attribute for manual override, localStorage for persistence, and a synchronous head script to prevent flashing. Provide an accessible three-state toggle (light/system/dark) for the best user experience.
Frequently asked questions
Is the “Automatic and Manual Dark Mode Toggle” lesson free?
Yes — the full text of “Automatic and Manual Dark Mode Toggle” is free to read here on the web, and the CSS Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the CSS Academy course, upgrade to CoddyKit PRO.
What will I learn in “Automatic and Manual Dark Mode Toggle”?
Build a theme toggle that respects system preference by default and lets users override it manually. You practise CSS Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start CSS Academy?
No prior experience is required. CSS Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Automatic and Manual Dark Mode Toggle” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this CSS Academy lesson?
Yes. Every CSS Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- prefers-color-scheme Media Query
- CSS Variables for Theming
- color-scheme Property
- Automatic and Manual Dark Mode Toggle