The prefers-color-scheme media query reads the user's operating system preference directly - no toggle switch needed to get a sensible default.
:root {
--bg: #ffffff;
--text: #12192b;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #12192b;
--text: #f2ede3;
}
}
body { background: var(--bg); color: var(--text); }
Building on custom properties makes this painless
Because we've already moved colour values onto CSS custom properties on most projects, adding dark mode is usually just a second block of variable overrides - the actual component CSS never needs to change.
A manual toggle, layered on top
document.documentElement.dataset.theme = 'dark';
/* :root[data-theme="dark"] { ... } overrides the system preference */
A user-facing toggle that overrides the system default is a nice-to-have, not a requirement - but worth the extra few lines once the variable-based system is already in place.
Respect the system preference before you build a toggle
@media (prefers-color-scheme: dark) {
:root { --bg: #12192b; --text: #f2ede3; }
}
This one media query gets a site to a correct dark mode for the majority of visitors who already have a system preference set, with no toggle, no JavaScript, and no flash of the wrong theme on load - because it's resolved before the page even paints.
Adding a manual override without breaking the default
A toggle should override the system preference, not replace it - someone who never touches the toggle should still get their OS setting respected. That means storing the override in localStorage only once someone actively chooses it, and falling back to the media query otherwise:
[data-theme="dark"] { --bg: #12192b; }
[data-theme="light"] { --bg: #fdfcfa; }
/* only set data-theme via JS after an explicit user click */