Sub topic 6
Theming and Dark Mode
This chapter assumes you can declare custom properties, read them with var(), and explain how they inherit down the element tree. It also assumes you know basic media queries and attribute selectors. The JavaScript here is minimal. A later chapter covers setProperty and getComputedStyle in depth.
A theme is a set of values for the same group of custom properties. Rules elsewhere in the stylesheet read those properties and never change. To switch themes, you redefine the values at some scope. This chapter covers how to organize the properties, how to follow the operating system setting, how to let the user override it, and where the pattern breaks.
Two layers of tokens
A maintainable theme separates two kinds of custom properties:
- Primitive tokens name raw values, such as
--blue-600: #0b5fff. They describe what exists in the palette and usually do not change between themes. - Semantic tokens name a role, such as
--bg,--fg, or--accent. They are the only properties that component rules read. Each theme assigns different primitives to them.
:root {
/* primitives */
--gray-50: #f8f9fb;
--gray-900: #111418;
--blue-600: #0b5fff;
--blue-300: #7aa7ff;
/* semantic tokens, light theme */
--bg: var(--gray-50);
--fg: var(--gray-900);
--accent: var(--blue-600);
}
body {
background: var(--bg);
color: var(--fg);
}
a {
color: var(--accent);
}The rules for body and a do not mention a theme. If you redefine --bg, --fg, and --accent, the whole page changes. A component that reads --gray-900 directly would ignore the theme, so keep primitives out of component rules.
Following the operating system with prefers-color-scheme
The prefers-color-scheme media feature reports whether the user's system or browser is set to a light or dark appearance. Put the light values on :root as the default, then override them inside the media query.
:root {
--bg: #ffffff;
--fg: #111111;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111111;
--fg: #eeeeee;
}
}
body {
background: var(--bg);
color: var(--fg);
}Both :root rules have the same specificity. The one inside the media query comes later in source order, so it wins when the query matches. If you moved the media block above the base block, the base values would always win and dark mode would never appear.
Tell the browser about your color scheme
Custom properties only affect the things you style. Built-in form controls, scrollbars, and the default page background come from the browser. The color-scheme property tells the browser which schemes your page supports, so these elements follow along.
:root {
color-scheme: light dark;
}With this declaration, an unstyled <input> or scrollbar adapts to the user's preference. You can also set color-scheme: dark inside a manual dark theme, which is shown below. It is a normal inherited property, so it can be scoped like a custom property.
Letting the user choose with an attribute
Many sites offer a toggle in addition to following the system. A common approach is a data-theme attribute on the <html> element. The attribute selector redefines the same custom properties.
:root {
--bg: #ffffff;
--fg: #111111;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111111;
--fg: #eeeeee;
}
}
[data-theme="dark"] {
--bg: #111111;
--fg: #eeeeee;
}
body {
background: var(--bg);
color: var(--fg);
}This version has a bug. Suppose the user's system is dark, and they choose "light" in your toggle, so the page has data-theme="light". No [data-theme="light"] rule exists, so the media query still applies and the page stays dark. The explicit choice must beat the system preference in both directions.
The three-state pattern
Treat the attribute as having three states: unset (follow the system), light, and dark. The media query should apply only when the user has not chosen light.
:root {
color-scheme: light dark;
--bg: #ffffff;
--fg: #111111;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #111111;
--fg: #eeeeee;
}
}
:root[data-theme="dark"] {
--bg: #111111;
--fg: #eeeeee;
}The dark values appear twice. This duplication comes from the language. Custom properties cannot be used in a media query condition, and CSS has no way to say "apply this block if the media query matches or the attribute is set". If duplication bothers you, a build step such as a Sass mixin or a PostCSS plugin can generate both blocks from one definition. Keep them next to each other in the file so they are edited together.
The table shows which rule decides the result in each case.
| `data-theme` | System preference | Result | Deciding rule |
|---|---|---|---|
| not set | light | light | base `:root` |
| not set | dark | dark | media query with `:not([data-theme="light"])` |
| `light` | dark | light | base `:root`, because the media rule is excluded |
| `dark` | light | dark | `:root[data-theme="dark"]` |
The next diagram shows how the final theme is chosen.
Switching and remembering the choice
A toggle needs a few lines of JavaScript. It sets the attribute and saves the choice in localStorage, which keeps small strings between visits.
const root = document.documentElement;
const button = document.querySelector('#theme-toggle');
function currentTheme() {
if (root.dataset.theme) return root.dataset.theme;
return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
button.addEventListener('click', () => {
const next = currentTheme() === 'dark' ? 'light' : 'dark';
root.dataset.theme = next;
localStorage.setItem('theme', next);
});Restoring the saved choice has a timing problem. If you apply it in a script at the end of <body>, the browser may paint the page in the system theme first and then switch. The user sees a flash. To avoid this, run a small inline script in <head>, before the stylesheet is applied to content.
<script>
const saved = localStorage.getItem('theme');
if (saved === 'light' || saved === 'dark') {
document.documentElement.dataset.theme = saved;
}
</script>Deriving a theme from a few inputs
Because custom properties work inside functions, a theme can be generated from a small number of inputs. One common input is a hue. The hsl() function accepts a var() for any component, so changing one number rebuilds the palette.
:root {
--hue: 220;
--accent: hsl(var(--hue) 90% 45%);
--accent-soft: hsl(var(--hue) 90% 95%);
--accent-strong: hsl(var(--hue) 90% 30%);
}
[data-brand="green"] {
--hue: 150;
}This example has a catch, which the next section explains. Setting --hue on [data-brand="green"] does not change --accent unless --accent is also computed at that element.
Scoped themes and when var() is resolved
Because custom properties inherit, you can theme a single region of the page, such as an inverted footer or a preview panel, by redefining properties on that element.
.panel-inverse {
--bg: #111111;
--fg: #eeeeee;
background: var(--bg);
color: var(--fg);
}Everything inside .panel-inverse now sees the dark values. This works for direct uses of --bg and --fg. It fails for derived tokens, which is a frequent source of confusion.
When a custom property's value contains var(), the browser substitutes the referenced value at the element where the property is declared. The resolved result is what descendants inherit. Consider this code:
:root {
--surface: #ffffff;
--surface-raised: var(--surface);
}
.panel-inverse {
--surface: #111111;
}--surface-raised was resolved on :root to #ffffff. Elements inside .panel-inverse inherit that resolved value, not the var(--surface) expression. They get --surface: #111111 but still --surface-raised: #ffffff.
The fix is to declare the derived token wherever the inputs may change. The simplest method is to declare derived tokens on the same selector as the scope that changes their inputs.
:root,
.panel-inverse {
--surface-raised: var(--surface);
}
:root {
--surface: #ffffff;
}
.panel-inverse {
--surface: #111111;
}Now .panel-inverse recomputes --surface-raised from its own --surface. The same reasoning explains the --hue example above: --accent must be declared on [data-brand="green"] too, or a wider selector must cover both. For a theme applied at :root through an attribute on <html>, this issue does not appear, because the attribute and the derived tokens live on the same element.
Practical details
Transitions between themes
Animating a theme switch is possible by transitioning the real properties that use the tokens:
body {
background: var(--bg);
color: var(--fg);
transition: background-color 0.2s, color 0.2s;
}Do not try to transition --bg itself. An unregistered custom property is treated as a token stream and changes instantly. Registering it with @property makes it animatable, which a later chapter covers. Also consider turning transitions off on first load, or the page may fade in from the wrong theme.
Contrast in both themes
A dark theme is not an inversion of the light one. Pure white text on pure black can look harsh, and a mid-blue link that passes contrast on white may fail on near-black. Pick the accent separately for each theme, as the primitives --blue-600 and --blue-300 allow, and check contrast ratios for both.
Images and other non-CSS colors
Custom properties do not recolor raster images. Options include supplying a second image with a <picture> element and a prefers-color-scheme media attribute, or using inline SVG where fill: var(--fg) works. An SVG loaded through <img> cannot read the page's custom properties.
Summary of approaches
| Approach | Follows system | User override | Cost |
|---|---|---|---|
| Media query only | yes | no | Simplest, no JavaScript |
| Attribute only | no | yes | Needs JavaScript to set the initial value |
| Media query plus attribute with `:not([data-theme="light"])` | yes | yes | Dark values written twice, small script |
Exercise
A page uses the media query and [data-theme="dark"] rules, but has no [data-theme="light"] rule and no :not(). A user on a dark-mode system clicks your toggle to choose light, and the page stays dark. Why, and what is the smallest CSS change that fixes it?
Show answer
The media query still matches because it only checks the system preference, and nothing in CSS stops it when data-theme="light" is set. Change the selector inside the media query from :root to :root:not([data-theme="light"]). The base :root values then apply when the attribute is light, and the dark values still apply when the attribute is dark through the separate :root[data-theme="dark"] rule.
Exercise
You declare --card-bg: var(--surface); on :root, then set --surface: #222; on .sidebar. Elements in .sidebar that use var(--card-bg) still show the root surface color. Explain why, and show one way to fix it.
Show answer
The var(--surface) in --card-bg was substituted on :root, so --card-bg holds the root value, and descendants inherit that resolved value. .sidebar changes --surface but never recomputes --card-bg. To fix it, declare --card-bg: var(--surface); on .sidebar as well, for example with the selector list :root, .sidebar { --card-bg: var(--surface); }.