Sub topic 2
How `var()` Substitution Works and Invalid Values
Assume you know CSS selectors, the cascade, inheritance, and basic HTML. Custom properties are token sequences, so the browser often delays checking their meaning until it substitutes them into a normal property.
Substitution and invalid values
var(--name) inserts the current value of --name into a declaration. Its second argument is a fallback used when the custom property is missing or has an invalid value.
.card {
color: var(--card-color, #222);
border-color: var(--card-border, var(--brand-color, gray));
}Fallbacks can be nested. However, a fallback does not repair every error. If substitution produces a value that is invalid for the property, the whole declaration becomes invalid at computed-value time.
:root {
--gap: 12px;
}
.panel {
/* Invalid: color cannot use a length. */
color: var(--gap);
/* Valid: the fallback is used because --missing is undefined. */
margin: var(--missing, 1rem);
}When a declaration becomes invalid at computed-value time, the browser uses the property’s inherited or initial value according to that property’s rules. This can make the failure appear far from the original custom property declaration.
> callout note > Use fallbacks for missing tokens, but also choose fallback values that are valid for the property receiving them.
Building scales with `calc()`
Custom properties become useful design tokens when combined with functions such as calc(). Keep compatible units in the expression and include spaces around arithmetic operators.
:root {
--space: 8px;
--text-size: 1rem;
}
.card {
padding: calc(var(--space) * 2);
gap: calc(var(--space) / 2);
font-size: var(--text-size);
}The browser substitutes the tokens first, then evaluates calc(). This lets one change to --space update several related dimensions.
Theming and dark mode
Put default tokens on :root, then redefine them in a media query or on an attribute. The rules using the tokens do not need to change.
:root {
--bg: #fff;
--fg: #111;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111;
--fg: #eee;
}
}
[data-theme="dark"] {
--bg: #111;
--fg: #eee;
}
body {
background: var(--bg);
color: var(--fg);
}The media query follows the operating-system preference. The attribute gives the application an explicit user choice.
Exercise
Why does color: var(--size, blue) remain invalid when --size: 12px?
Show answer
--size exists, so blue is not selected. After substitution, 12px is invalid for color, making the declaration invalid.