Sub topic 8
Dark Mode with prefers-color-scheme and color-scheme
This chapter assumes you know how custom properties are declared, how var() resolves, and how they inherit. It also assumes you know the primitive and semantic token tiers. Here you will use those tiers to add a dark theme. Components stay unchanged, and only semantic tokens get new values.
Why dark mode fits the token model
A dark theme is a second set of values for the same roles. A card still needs a surface color and a text color. Only the colors that fill those roles change. If components reference --color-surface and --color-text and never #f9fafb, a dark theme is a handful of overrides in one place.
Two separate browser features take part, and they are easy to confuse:
prefers-color-schemeis a media feature. It reports whether the user's operating system or browser is set to light or dark. You use it to choose which token values apply.color-schemeis a CSS property. It tells the browser which schemes your page supports, so the browser can restyle its own built-in UI to match.
You normally need both.
Reading the user's preference
The prefers-color-scheme media feature matches dark or light. Users who have not chosen a preference match light, and in current browsers that is also the value reported when the system gives no signal.
The simplest dark mode redefines the semantic tokens inside a media query:
:root {
--color-bg: #ffffff;
--color-text: #111827;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0b1020;
--color-text: #e5e7eb;
}
}
body {
background: var(--color-bg);
color: var(--color-text);
}Both :root rules have the same specificity, so the later one wins when the media query matches. Keep the media block after the base block. If you reverse them, the light values override the dark ones even in dark mode.
The body rule never mentions a theme. It reads --color-bg and --color-text, and the browser resolves them to whichever values currently apply.
Letting the user override the system
A system preference is a default. Many sites add a toggle so a visitor can pick light or dark regardless of the system. This creates three states: follow the system, force light, and force dark.
A data-theme attribute on the root element represents the forced states. The CSS needs to handle three cases:
:root {
--color-bg: #ffffff;
--color-text: #111827;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--color-bg: #0b1020;
--color-text: #e5e7eb;
}
}
[data-theme="dark"] {
--color-bg: #0b1020;
--color-text: #e5e7eb;
}Walk through each state:
- No attribute, system is light: only the base
:rootrule applies. - No attribute, system is dark: the media query matches and
:not([data-theme="light"])is true, so the dark values apply. data-theme="light": the:not()excludes the media rule, so the base values apply even when the system is dark.data-theme="dark": the attribute selector applies the dark values whatever the system says.
The dark values appear twice. Plain CSS has no way to share a block between a media query and an attribute selector. You can live with the duplication in a small stylesheet. For a large token set, generate both blocks from one source, which a later chapter covers.
Specificity matters here. :root:not([data-theme="light"]) counts as two pseudo-class-level selectors, because :not() takes the specificity of its argument. [data-theme="dark"] has one. The rules do not conflict, because the two states are mutually exclusive.
The decision path
The flowchart shows how the browser picks values for the three states.
Building dark values from primitives
Do not write raw hex values in the dark block when you already have primitives. Map the semantic roles to different primitives, so the palette stays defined in one place:
:root {
/* Primitives: never change per theme */
--color-gray-50: #f9fafb;
--color-gray-100: #f3f4f6;
--color-gray-200: #e5e7eb;
--color-gray-800: #1f2937;
--color-gray-900: #111827;
--color-gray-950: #0b1020;
--color-blue-400: #60a5fa;
--color-blue-600: #2563eb;
/* Semantic: light values */
--color-bg: var(--color-gray-50);
--color-surface: #ffffff;
--color-text: var(--color-gray-900);
--color-accent: var(--color-blue-600);
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: var(--color-gray-950);
--color-surface: var(--color-gray-900);
--color-text: var(--color-gray-200);
--color-accent: var(--color-blue-400);
}
}
.card {
background: var(--color-surface);
color: var(--color-text);
border: 1px solid var(--color-gray-800);
}Primitives stay on :root and are never overridden. Only semantic tokens change.
The .card border above uses a primitive directly, which breaks this rule. In light mode --color-gray-800 is a heavy dark line on a white card. Add a --color-border semantic token and override it per theme. A component that reaches for a primitive will not follow the theme.
Dark values also need design care, not just inversion:
- Pure black backgrounds with pure white text cause glare. Use a very dark gray and an off-white.
- Raised surfaces such as cards and menus usually get lighter in dark mode, where in light mode they often get a shadow.
- Saturated accents can vibrate on dark backgrounds. A lighter, slightly less saturated variant, like
--color-blue-400above, is easier to read. - Check text contrast again for the dark pair. WCAG asks for at least 4.5:1 for body text.
The color-scheme property
Your tokens style your own elements. They do not style the browser's built-in UI: form controls, scrollbars, the default page background, and default link and text colors. Without help, those stay light even when your page is dark. You get a dark page with a white scrollbar and a white <input>.
The color-scheme property fixes this. It declares which schemes the element supports, and the browser adjusts its defaults to match.
:root {
color-scheme: light dark;
}With light dark, the browser follows the system preference for built-in UI. To pin a theme, set a single value. Combine this with the attribute states:
:root {
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
color-scheme: dark;
}
}
[data-theme="dark"] {
color-scheme: dark;
}color-scheme inherits, so setting it on :root covers the whole page. You can also set it on a subtree, for example color-scheme: dark on a footer that is always dark.
Add a matching meta tag in the document head. The browser reads it before any CSS loads, so the default canvas is already the right color while the stylesheet downloads:
<meta name="color-scheme" content="light dark">light-dark() as a shorter form
The light-dark() function takes two colors and returns the first in a light scheme and the second in a dark one. It needs a color-scheme that is active on the element, and it only accepts color values:
:root {
color-scheme: light dark;
--color-bg: light-dark(#ffffff, #0b1020);
--color-text: light-dark(#111827, #e5e7eb);
}
body {
background: var(--color-bg);
color: var(--color-text);
}This removes the duplicated block. It also follows data-theme automatically if you set color-scheme: light or color-scheme: dark from the attribute. It cannot change non-color tokens such as shadows expressed as lengths or font weights, and it needs a browser recent enough to support it. For those cases, keep the media query approach.
Remembering the choice
A toggle needs to store the choice and apply it before the page paints. If the script runs late, the page flashes the wrong theme first. Put a small inline script in the <head>, before the stylesheet-dependent content renders:
<script>
try {
const saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.dataset.theme = saved;
}
} catch (e) {
/* Storage can be blocked; fall back to the system preference */
}
</script>The script only sets the attribute. All visual decisions stay in CSS. Removing the attribute returns the page to following the system.
Choosing a mechanism
| Mechanism | What it controls | Use it when |
|---|---|---|
| `@media (prefers-color-scheme)` | Which token values apply, based on the system | You need any theme-dependent value, not only colors |
| `data-theme` attribute | Which token values apply, based on a user choice | You offer a manual toggle |
| `color-scheme` | Browser-drawn UI and default colors | Always, on any page with a dark theme |
| `light-dark()` | A single color token with two values | You want less duplication and only colors change |
Common mistakes
- Forgetting
color-scheme. Symptoms are light scrollbars, white form fields, and a white flash on overscroll. - Hard-coding a color in a component, such as
color: #333. That element stays dark gray on a dark background. Search your CSS for hex values outside the token file. - Placing the media query before the base block, so the base values win.
- Using
var()inside a media query condition.@media (min-width: var(--bp))does not work. Custom properties cannot be used in media conditions. - Testing only your own system setting. In Chrome and Edge DevTools, open the Rendering panel and use "Emulate CSS media feature prefers-color-scheme". Firefox has light and dark buttons in the Inspector toolbar.
- Forgetting images. A logo with a dark wordmark disappears on a dark surface. Provide a second image with
<picture>and amedia="(prefers-color-scheme: dark)"source, or use an SVG that readscurrentColor.
Exercises
Exercise
A page sets --color-bg in :root and overrides it inside @media (prefers-color-scheme: dark) { :root { ... } }. The media block is written before the base :root block in the file, and dark-mode users still see light colors. Why, and how do you fix it?
Show answer
Both rules have the same specificity (:root), so the one later in the source wins. The base block comes last, so its light values override the dark ones even when the media query matches. Move the media block after the base block.
Exercise
A user whose system is set to dark clicks your toggle to force light mode, which sets data-theme="light" on the root element. Which selector stops the dark media query from applying, and why does a forced dark theme need its own [data-theme="dark"] rule?
Show answer
:root:not([data-theme="light"]) inside the media query stops the dark values from applying when the attribute is light, so the base light values are used. A forced dark theme needs its own rule because a user whose system is light will not match the media query, so only the attribute selector can apply the dark values for them.
Exercise
Your dark theme looks right, but the page scrollbar and a text <input> are still light. What single declaration on the root element addresses this, and what meta tag helps avoid a white flash while CSS loads?
Show answer
color-scheme: light dark; on :root (or color-scheme: dark when forcing dark) makes the browser draw scrollbars and form controls in the matching scheme. The tag <meta name="color-scheme" content="light dark"> in the head lets the browser choose the right default canvas before the stylesheet arrives.