Sub topic 7
Adding a light, dark, and system toggle
This chapter assumes you can write CSS custom properties, you have seen the prefers-color-scheme media query, and you can read and set DOM attributes in JavaScript. It builds on the semantic color tokens and the color-scheme property from the earlier chapters. By the end you will have a three-way control with the choices Light, Dark, and System, driven by one attribute on the root element.
Why a toggle needs three states
A page that follows the operating system works for most visitors. Some want something different. A person with a bright laptop in a dim room may want dark mode even though the system is set to light. Another person may want light mode in a browser while the rest of the desktop is dark.
A two-state switch (light or dark) has a flaw. Once the visitor clicks it, you have no way to return to "follow my system". The third state fixes this.
| Choice | Meaning | `data-theme` on `<html>` |
|---|---|---|
| Light | Always light, ignore the system | `light` |
| Dark | Always dark, ignore the system | `dark` |
| System | Follow the operating system | attribute absent |
The key design decision is that System is represented by the absence of the attribute. The stylesheet then only needs two kinds of rules: the automatic rule, which applies when no override exists, and the explicit rules, which apply when the visitor has chosen.
How the pieces fit together
Both the light branch and the dark branch can be reached from two different paths. That is why the CSS in the next section has to express the dark values in two places.
The CSS: an override that beats the system
Start with tokens that hold the light colors by default. Then override them in three places.
:root {
color-scheme: light dark;
--bg: #ffffff;
--text: #1a1a1a;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #121212;
--text: #e6e6e6;
}
}
:root[data-theme="light"] {
color-scheme: light;
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #121212;
--text: #e6e6e6;
}
body {
background: var(--bg);
color: var(--text);
}Here is what each block does:
- The first
:rootblock sets the light tokens and declares that the page supports both schemes. This is the state for a visitor on a light system with no override. - The media query applies dark tokens when the system is dark. The
:not([data-theme="light"])part is the important piece. If the visitor forced light, the query still matches (the system really is dark), so the selector must exclude that case. :root[data-theme="light"]pinscolor-schemetolight. The tokens already hold light values, so nothing else is needed. Pinning matters for built-in UI such as form controls and scrollbars, which followcolor-scheme, not your tokens.:root[data-theme="dark"]sets the dark tokens andcolor-scheme: dark, regardless of the system.
Notice that the dark values appear twice, once in the media query and once in the explicit rule. This duplication is the main cost of the attribute approach. A later section shows a way to remove it.
The markup: a three-button control
Use real buttons so the control works with a keyboard and screen readers. Each button reports whether it is the active choice through aria-pressed.
<div role="group" aria-label="Color theme">
<button type="button" data-theme-choice="light" aria-pressed="false">Light</button>
<button type="button" data-theme-choice="dark" aria-pressed="false">Dark</button>
<button type="button" data-theme-choice="system" aria-pressed="true">System</button>
</div>The buttons use data-theme-choice, not data-theme. This keeps them separate from the attribute on <html> that the CSS reads. The two names are close, so keep that difference in mind when you debug.
The JavaScript: apply, save, and reflect
The script has three jobs. It applies a choice to the root element, saves the choice, and updates the buttons to show which one is active.
const root = document.documentElement;
const STORAGE_KEY = "theme";
const buttons = document.querySelectorAll("[data-theme-choice]");
function applyTheme(choice) {
if (choice === "light" || choice === "dark") {
root.dataset.theme = choice;
} else {
delete root.dataset.theme;
}
}
function updateButtons(choice) {
buttons.forEach((button) => {
const active = button.dataset.themeChoice === choice;
button.setAttribute("aria-pressed", String(active));
});
}
function setChoice(choice) {
applyTheme(choice);
updateButtons(choice);
if (choice === "system") {
localStorage.removeItem(STORAGE_KEY);
} else {
localStorage.setItem(STORAGE_KEY, choice);
}
}
buttons.forEach((button) => {
button.addEventListener("click", () => {
setChoice(button.dataset.themeChoice);
});
});
const saved = localStorage.getItem(STORAGE_KEY);
const initial = saved === "light" || saved === "dark" ? saved : "system";
applyTheme(initial);
updateButtons(initial);A few details are worth pointing out:
delete root.dataset.themeremoves the attribute entirely. Setting it to an empty string or to"system"would leave an attribute behind. It would not match any rule, so the page would still follow the system, but the:not([data-theme="light"])logic is clearer when the attribute is truly absent.- Choosing System removes the stored value instead of storing the string
"system". A missing key then means "no preference", which is also what a first-time visitor has. - The code validates the saved value.
localStoragecan contain anything, because other scripts or older versions of your site may have written to it. Onlylightanddarkare accepted. Everything else falls back to System.
Keeping System live
When the choice is System, the browser changes the theme on its own when the operating system switches, for example at sunset. Your CSS handles this with no JavaScript, because the media query is re-evaluated automatically.
You only need to listen for changes if your script keeps its own copy of the current theme. A canvas chart that draws with hard-coded colors is an example. In that case, subscribe to the media query:
const query = window.matchMedia("(prefers-color-scheme: dark)");
query.addEventListener("change", (event) => {
const choice = localStorage.getItem("theme");
if (choice !== "light" && choice !== "dark") {
console.log("System theme changed. Dark is now", event.matches);
}
});The listener ignores the event when the visitor has made an explicit choice, because the explicit choice wins.
Removing the duplicated dark values with light-dark()
The duplication in the CSS comes from having to write the dark tokens twice. The light-dark() function removes it. It picks its first argument when the element's used color scheme is light and its second when it is dark. The used scheme comes from color-scheme. Since your attribute rules already set color-scheme, the toggle works without any token values in the media query.
:root {
color-scheme: light dark;
}
:root[data-theme="light"] {
color-scheme: light;
}
:root[data-theme="dark"] {
color-scheme: dark;
}
body {
background: light-dark(#ffffff, #121212);
color: light-dark(#1a1a1a, #e6e6e6);
}With color-scheme: light dark and no attribute, the browser uses the system preference. With the attribute, the scheme is forced. No media query is needed at all.
There is a trade-off. Each light-dark() call is written at the point of use, so changing a palette color means editing every place that uses it. You can recover the token structure by putting the calls inside custom properties:
:root {
--bg: light-dark(#ffffff, #121212);
--text: light-dark(#1a1a1a, #e6e6e6);
}Be aware of one gotcha with this pattern. A custom property holding light-dark() is not resolved where it is declared. The function is evaluated where the value is used, so the used scheme at that element decides the result. That is usually what you want, but it can surprise you if you nest a component with its own color-scheme.
Also check browser support for light-dark() before relying on it. It is newer than the media query. If you must support older browsers, keep the media-query version.
Common errors
- The toggle does nothing in dark system mode. Check that the dark tokens in the media query are scoped with
:not([data-theme="light"]). Without it, forcing light has no visible effect on a dark system. - Form controls stay light in dark mode.
color-schemeis missing or is overridden tolight. Built-in controls follow it, not your custom properties. - The buttons show the wrong state after reload.
updateButtonswas not called with the initial value. CallingapplyThemealone changes the page but not the control. - System stops following the OS. An old value is still in
localStorage. Choosing System must callremoveItem, as the example does. - Selector typos pass silently. CSS ignores a selector that matches nothing. If the theme does not change, inspect
<html>in the Elements panel and confirm that thedata-themeattribute appears and disappears as you click.
Exercise
A visitor's operating system is set to dark. They click "Light" on your site. Using the first CSS example in this chapter, explain which rules apply and why the page stays light. Then say what must change in the JavaScript if you want "System" to restore the dark appearance.
Show answer
The media query matches because the system is dark, but its selector is :root:not([data-theme="light"]). The script has set data-theme="light" on <html>, so the selector does not match and the dark tokens are not applied. The light tokens from the base :root block stay in effect, and :root[data-theme="light"] sets color-scheme: light so built-in controls match. To restore dark with System, the script must remove the data-theme attribute (delete root.dataset.theme) and remove the saved value from localStorage. With no attribute, the :not() selector matches again and the dark tokens apply.