Sub topic 3
Storing colors in custom properties
This chapter covers CSS custom properties, the mechanism that lets a dark theme change colors without rewriting every rule. It assumes you know CSS selectors, the cascade and specificity, and hex and rgb() colors. It also assumes you can read basic JavaScript that touches the DOM. The previous chapter showed that prefers-color-scheme reports the user's system setting. Here you build the storage layer that setting will switch.
Why dark mode needs variables
Suppose a site uses #ffffff as its background in 40 rules. A dark theme needs a different value in every one of them. You could write a second set of 40 rules inside a media query, but then every future color change must be made twice, and the two copies drift apart.
A custom property solves this by giving a value a name. You write the color once, refer to it by name everywhere, and change the value in one place to change the whole theme.
Declaring and using a custom property
A custom property is any property whose name starts with two hyphens. You read its value with the var() function.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--link: #0b5fff;
}
body {
background: var(--bg);
color: var(--text);
}
a {
color: var(--link);
}A few facts about the syntax matter in practice:
- Names are case-sensitive.
--Bgand--bgare two different properties. - The browser does not check the value when it parses the declaration.
--bg: banana;is accepted. Validation happens later, where you usevar(--bg). - Custom properties are not limited to colors. They can hold lengths, numbers, font stacks, or any fragment of CSS.
:rootmatches the<html>element. It has the same effect ashtmlbut with higher specificity, which is useful later when you override values.
How values are inherited
Custom properties inherit by default, like color and font-family. If you declare --text on :root, every element in the document can read it, because each element inherits it from its parent.
This explains why :root is the usual place for theme colors. A value declared there is available to the whole page.
Inheritance also gives you scoping. You can redefine a property on any element, and only that element and its descendants see the new value.
:root {
--surface: #f4f4f4;
--text: #1a1a1a;
}
.card {
background: var(--surface);
color: var(--text);
}
.card.inverted {
--surface: #1a1a1a;
--text: #f4f4f4;
}The .card rule never changes. The .inverted variant works because it supplies different values for the names that .card already reads. A dark theme uses the same idea, applied at the :root level.
Overriding values for dark mode
Once colors live in properties, the dark theme becomes a small block that reassigns them. This is the same pattern from the topic overview, now with a clear explanation of why it works.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--link: #0b5fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--text: #e6e6e6;
--link: #8ab4ff;
}
}
body {
background: var(--bg);
color: var(--text);
}
a {
color: var(--link);
}The media query does not touch body or a. It only changes what --bg, --text, and --link mean on :root. Because the two :root rules have equal specificity, the one that comes later wins when the media query matches, so the dark block must come after the light defaults.
Note what you cannot do: you cannot put var() inside a media query condition. @media (min-width: var(--breakpoint)) does not work, because custom properties are resolved per element and a media query is evaluated for the whole document.
Fallback values
var() accepts a second argument, used when the property is not defined.
.badge {
background: var(--badge-bg, #dddddd);
color: var(--badge-text, var(--text, #1a1a1a));
}Everything after the first comma is the fallback, including any further commas. Fallbacks can be nested, as in --badge-text above. They are useful for components that may be dropped into pages with different theme setups. Do not use them to replace a missing definition in your own theme. A fallback hides the mistake, and then you have a color that does not change in dark mode.
Invalid at computed-value time
This is the least intuitive behavior of custom properties, and it causes many dark mode bugs.
Because the browser does not validate a custom property's value when it parses it, an error shows up only when var() is substituted into a real property. If the result is not valid for that property, the declaration becomes invalid at computed-value time. The browser does not skip it and fall back to an earlier rule in the cascade. It treats the property as unset, which means the inherited value for inherited properties like color, or the initial value for others like background-color.
:root {
--bg: 16px; /* a length, not a color */
}
body {
background: #ffffff;
background: var(--bg); /* invalid at computed-value time */
}A developer might expect the first background to act as a fallback. It does not. The second declaration wins in the cascade, then fails during substitution, and background becomes transparent. You see no error in the console. The only clue is in the DevTools Computed pane, where the property shows as unset or the declaration is struck through as invalid.
Splitting a color into channels
Sometimes you want one base color at several opacities. A custom property can hold only the channel numbers, and you add the alpha where you use it.
:root {
--accent-rgb: 11 95 255;
}
.highlight {
background: rgb(var(--accent-rgb) / 0.15);
border: 1px solid rgb(var(--accent-rgb) / 0.6);
}
@media (prefers-color-scheme: dark) {
:root {
--accent-rgb: 138 180 255;
}
}This uses the space-separated rgb() syntax, which current browsers support. It works because the custom property holds raw text, and var() pastes that text into the function. The dark block changes one line, and every opacity variant follows.
Reading and writing properties from JavaScript
Custom properties are part of the style system, so scripts can read and change them. This matters for the toggle you will build later.
const root = document.documentElement;
// Read the computed value of --bg on <html>.
const bg = getComputedStyle(root).getPropertyValue("--bg").trim();
console.log(bg); // "#ffffff" in light mode, "#121212" in dark mode
// Override it for the whole page.
root.style.setProperty("--bg", "#202020");
// Remove the inline override so the stylesheet applies again.
root.style.removeProperty("--bg");Two details are worth remembering. getPropertyValue returns the text as written, often with leading whitespace, so call .trim(). And an inline style.setProperty has higher priority than any stylesheet rule, including your media query, so it overrides the system-driven dark theme. For a full toggle, changing an attribute and letting the stylesheet respond is usually cleaner than setting individual colors from script.
Transitions and registered properties
By default, the browser treats a custom property as an unknown string, so it cannot animate between two values. A transition on --bg itself does nothing. You can still transition the real property that uses it:
body {
background: var(--bg);
color: var(--text);
transition: background-color 200ms ease, color 200ms ease;
}When the theme changes, --bg changes, the computed background changes, and that change animates. If you do need to animate the custom property directly, you can register it with a type using @property:
@property --bg {
syntax: "<color>";
inherits: true;
initial-value: #ffffff;
}A registered property is validated as a color at parse time, which also gives you earlier error detection. Support for @property is good in current browsers but check your target list before relying on it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Color does not change in dark mode | The rule uses a literal like `#fff` instead of `var(--bg)` | Replace the literal with the property |
| Dark values never apply | The dark block comes before the light defaults in the file | Move the media query after the base `:root` rule |
| Property ignored with no console error | Value is invalid for the target property | Inspect Computed styles and check the value type |
| `var(--Bg)` has no effect | Name case differs from the declaration | Match the exact case |
| Component ignores the theme | Property is declared on a sibling or child, not an ancestor | Declare it on `:root` or a common ancestor |
| Media query with `var()` never matches | `var()` is not allowed in media conditions | Use a literal value |
What comes next
You now have the mechanism: names for colors, inheritance from :root, and a media query that reassigns the names. The next chapter decides what the names should be. Names like --white stop making sense once the dark theme sets them to a dark color, so the next chapter introduces semantic tokens such as --surface and --text-muted.
Exercise
A page defines --bg: #ffffff; on :root and later adds @media (prefers-color-scheme: dark) { :root { --bg: #121212; } }. The body uses background: #ffffff; background: var(--bgg);. In dark mode the page background is transparent instead of dark. Give two separate problems with the body rule and say how the browser treats the second declaration.
Show answer
First, --bgg is a typo for --bg, so the property is not defined. Second, there is no fallback in var(). The browser does not discard the second declaration and use the first one. Because it wins in the cascade and then fails at substitution, it is invalid at computed-value time, and background becomes unset, which resolves to transparent. The fix is background: var(--bg);, optionally with a fallback such as var(--bg, #ffffff).
Exercise
You want .note to have a border in the accent color at 40% opacity, and you want the dark theme to change only one declaration to update it. Write the CSS.
Show answer
Store the channels in a property and add the alpha where you use it. For example: :root { --accent-rgb: 11 95 255; }, then .note { border: 1px solid rgb(var(--accent-rgb) / 0.4); }, then @media (prefers-color-scheme: dark) { :root { --accent-rgb: 138 180 255; } }. The dark block changes only --accent-rgb.