Sub topic 4
Fallback values with var()
This chapter assumes you can declare a custom property and read it with var(). You should also know that custom properties inherit down the tree. The earlier chapters on declaring properties and on cascade and inheritance cover both. Here you will learn exactly when a fallback applies, when it does not, and how to use fallbacks in a token system without hiding mistakes.
The syntax
var() takes a custom property name and an optional second argument, the fallback:
.badge {
padding: var(--badge-padding, 0.75rem);
}If --badge-padding has a usable value on the element, the browser substitutes that value. Otherwise it substitutes 0.75rem.
Everything after the first comma belongs to the fallback, including more commas. This matters for lists such as font stacks:
body {
font-family: var(--font-body, system-ui, "Segoe UI", sans-serif);
}Here the fallback is the whole list system-ui, "Segoe UI", sans-serif. You do not need extra parentheses or quotes. Whitespace around the fallback is trimmed.
A fallback can itself contain var(), so you can chain several levels:
.button {
background: var(--button-bg, var(--color-accent, #2563eb));
}The browser tries --button-bg. If that is missing, it tries --color-accent. If that is also missing, it uses the literal #2563eb. The browser only evaluates a fallback when it needs it.
When the fallback is used
The fallback is used when the referenced property holds the guaranteed-invalid value. This is the state of a custom property that has no value. It is not the same as a value that is wrong for the property you put it in.
A custom property is in the guaranteed-invalid state in these cases:
- No rule sets it on the element or on any ancestor it inherits from.
- It is set to the keyword
initial, which resets it to this state. - It forms a dependency cycle with other custom properties.
The table below lists the cases you will meet most often.
| Situation | Is the fallback used? |
|---|---|
| The property is never declared | Yes |
| The property is declared only on a sibling or descendant, so it does not reach this element | Yes |
| The property is set to `initial` | Yes |
| The property is set to an empty value, `--x: ;` | No. The empty value is valid and substitutes as nothing. |
| The property holds a value that is wrong for the consuming property | No. The declaration becomes invalid at computed-value time. |
| The property is registered with `@property` and has an `initial-value` | No. The initial value always exists. |
The next sections explain the two cases that surprise people.
Wrong values do not trigger the fallback
Custom properties accept almost any token sequence, so the browser cannot check a value when it reads the declaration. It checks only after substitution, when it knows which property will use the value. At that point it is too late to choose the fallback.
:root {
--pad: 2 rem; /* typo: a space between the number and the unit */
}
.card {
padding: 8px; /* this value is overridden below */
padding: var(--pad, 1rem);
}--pad is defined, so the browser substitutes 2 rem. That makes padding: 2 rem, which is not a valid padding. The declaration is then invalid at computed-value time. The browser does not return to the earlier padding: 8px rule, and it does not use 1rem. It treats the property as unset. padding is not inherited, so it falls back to its initial value, 0.
The result is a card with no padding and no error in the console. The DevTools Styles panel marks the declaration with a warning icon.
This behavior is why debugging tokens often starts with the Computed pane. Check whether the token exists, and then check whether its value suits the property that uses it.
Empty values and the initial keyword
An empty custom property is valid. This is occasionally useful, but it can cause trouble:
:root {
--shadow: ;
}
.card {
box-shadow: var(--shadow, 0 1px 3px rgb(0 0 0 / 0.2));
}--shadow has an empty value, so the fallback is skipped. The declaration becomes box-shadow: ;, which is invalid at computed-value time, and the card has no shadow. If you meant to clear the shadow, use none instead.
To return a token to the "not defined" state, use initial:
.card--flat {
--card-shadow: initial;
}
.card {
box-shadow: var(--card-shadow, 0 1px 3px rgb(0 0 0 / 0.2));
}Without initial, a variant could not undo an inherited value. If a parent sets --card-shadow, every card below it inherits that value. Setting initial on .card--flat makes the property undefined again for that element, so the fallback applies.
The flow of resolution
The diagram shows how the browser decides what to substitute.
Notice that the fallback also goes through the validity check. A fallback of 2 rem would fail in the same way.
Fallbacks in a token system
Fallbacks have three good uses in a token system.
Optional component tokens
A component can expose a hook that consumers may set, with a default from the shared scale:
:root {
--space-3: 0.75rem;
}
.badge {
padding: var(--badge-padding, var(--space-3));
}
.sidebar .badge {
--badge-padding: 0.25rem;
}The badge works without any setup. A parent or a variant can override one value by declaring --badge-padding. This keeps the badge free of any required declaration and still lets callers adjust it.
Defaults in isolated components
Library components may be used on pages that never load your root tokens. A fallback keeps them readable:
.alert {
color: var(--color-text, #111827);
background: var(--color-surface, #f9fafb);
}If the page defines the tokens, the component follows the theme. If it does not, the component still looks acceptable.
Gradual migration
During a migration you can reference a new token and fall back to the old one:
.nav {
background: var(--nav-bg, var(--legacy-header-bg));
}Remove the fallback once every page defines the new token.
When not to use fallbacks
Do not add a fallback to every var() call. Three problems follow from doing so:
- Typos disappear. With
var(--colour-text, #111), a misspelled name produces a plausible color, and the theme never reaches the element. - Values get duplicated. The literal in the fallback is a second copy of a decision that belongs in a primitive token. When the palette changes, the copy goes stale.
- Themes break quietly. A fallback that is a light color will not follow a dark theme if a semantic token is missing.
A useful rule is to leave fallbacks off in the main token chain, where a missing token is a bug you want to see. Use fallbacks only at boundaries, such as optional component hooks and reusable components.
Registered properties change the rules
A property registered with @property always has a value, because its initial-value is used when nothing else sets it. The fallback in var() is then never reached:
@property --accent-hue {
syntax: "<number>";
inherits: false;
initial-value: 220;
}
.button {
background: hsl(var(--accent-hue, 10) 80% 50%);
}The 10 is dead code here, because --accent-hue is always at least 220. If a registered property has no initial-value, the syntax must be *, so the fallback still works.
Registration also checks values at parse time. A rule such as --accent-hue: red; is dropped as invalid, so the property keeps its previous or initial value. That is a stronger safeguard than a fallback, and the later chapter on @property covers it.
Checking fallbacks in the browser
You can test which case applies from JavaScript. getPropertyValue returns an empty string for a property that is not defined:
const style = getComputedStyle(document.documentElement);
const value = style.getPropertyValue('--badge-padding').trim();
if (value === '') {
console.log('--badge-padding is not defined, so the fallback is used');
} else {
console.log(`--badge-padding is ${value}`);
}This check cannot tell an undefined property from an empty one, since both return an empty string. Use DevTools when you need to separate the two cases.
Summary of rules
- The fallback is used only when the token is in the guaranteed-invalid state.
- Everything after the first comma is the fallback, including commas.
- Fallbacks can nest, and the browser evaluates only the one it needs.
- A defined but unsuitable value makes the declaration invalid at computed-value time. It does not trigger the fallback.
initialreturns a token to the undefined state. An empty value does not.- Registered properties with an
initial-valuenever use the fallback.
Exercise
A stylesheet has :root { --gap: 1 rem; } and .list { gap: var(--gap, 8px); }. What gap does .list get, and why does the 8px fallback not apply?
Show answer
The gap property resets to its initial value, so the list has no gap (normal, which is 0 in flex and grid layouts). --gap is defined, so it is not in the guaranteed-invalid state and the fallback is skipped. The browser substitutes 1 rem, which is not a valid gap value because of the space. The declaration becomes invalid at computed-value time and the property behaves as unset. Fixing the typo to 1rem solves it.
Exercise
A card variant must remove a --card-shadow value that its parent set, so that the card's own fallback shadow applies again. Which declaration on the variant achieves this, and why does --card-shadow: ; not work?
Show answer
Use --card-shadow: initial;. This resets the property to the guaranteed-invalid state, so var(--card-shadow, <default>) uses the fallback. An empty value is valid, so the fallback is skipped and box-shadow becomes invalid at computed-value time.
Exercise
Write a .tag rule that sets background from an optional --tag-bg token. If that is missing, it should use the semantic token --color-surface. If that is missing too, it should use #f9fafb.
Show answer
.tag { background: var(--tag-bg, var(--color-surface, #f9fafb)); }