Sub topic 2
Providing fallback values
This chapter covers the second argument of var(). It assumes you can already declare a custom property such as --brand-color: #0b5fff; and read it with var(--brand-color). It also assumes you know that custom properties inherit down the DOM tree. By the end you should be able to predict when a fallback is used and when it is ignored. You should also be able to write fallbacks that stay readable in a real stylesheet.
The syntax
The var() function takes a custom property name and an optional second argument:
.card {
color: var(--card-color, #222);
border-color: var(--card-border, var(--brand-color, gray));
}If --card-color has a usable value on the element, color uses it. Otherwise color is #222. The fallback is evaluated for each element and each time the declaration is computed. The same rule can therefore give different results on different elements, depending on which custom properties each element inherited.
The fallback is optional. var(--card-color) with no fallback is valid. If --card-color is missing, the declaration is not valid at computed-value time (covered below).
When the fallback is used
A fallback is used when the referenced custom property has no value on the element. In the specification's terms, its value is the guaranteed-invalid value. This happens in three situations:
- The property was never declared on the element or any ancestor.
- The property was explicitly reset with the CSS-wide keyword
initial. Custom properties have no built-in default, soinitialreturns them to the guaranteed-invalid state. - The property takes part in a dependency cycle, for example
--a: var(--b)together with--b: var(--a). Both become guaranteed-invalid, so avar()that references them and has a fallback uses it.
The following example shows all three. Save it as an HTML file and open it in a browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fallback triggers</title>
<style>
p {
margin: 0.25rem 0;
padding: 0.5rem;
background: var(--bg, lightgray);
}
.set { --bg: palegreen; }
.reset { --bg: palegreen; }
.reset > p { --bg: initial; }
.cycle { --a: var(--b); --b: var(--a); --bg: var(--a); }
</style>
</head>
<body>
<div>
<p>Never declared: gray fallback</p>
</div>
<div class="set">
<p>Declared on an ancestor: green</p>
</div>
<div class="reset">
<p>Reset with initial: gray fallback</p>
</div>
<div class="cycle">
<p>Cycle: gray fallback</p>
</div>
</body>
</html>In the .cycle block, --bg is var(--a), and --a is part of a cycle. That makes --a guaranteed-invalid, so --bg becomes guaranteed-invalid too, and the var(--bg, lightgray) on the paragraph takes the fallback.
Everything after the first comma is the fallback
The parser splits the arguments of var() at the first comma only. The rest of the text, including later commas, belongs to the fallback. This makes comma-separated values work without special escaping:
body {
font-family: var(--font-body, "Inter", "Helvetica Neue", Arial, sans-serif);
}
.shadowed {
box-shadow: var(--shadow, 0 1px 2px rgb(0 0 0 / 0.2), 0 4px 12px rgb(0 0 0 / 0.1));
}If --font-body is undefined, font-family receives the full list "Inter", "Helvetica Neue", Arial, sans-serif. You do not wrap the list in quotes or parentheses.
A fallback may also be empty. var(--x,) is valid and substitutes nothing when --x is missing. This is rarely useful on its own, but it appears in techniques where a variable optionally adds a token to a longer value.
Nested fallbacks
A fallback can itself contain var(), which lets you build a lookup chain from the most specific setting to the most general:
.card {
border-color: var(--card-border, var(--brand-color, gray));
}The browser reads this left to right:
- Use
--card-borderif it is defined. - Otherwise use
--brand-colorif it is defined. - Otherwise use
gray.
Chains work to any depth, but each level adds reading cost. When you find yourself writing three or more levels, consider whether a default declared once on :root would be clearer.
Fallbacks versus declared defaults
You have two places to supply a default. You can write it inline in var(), or you can declare it on a high-level selector such as :root.
/* Option A: default declared once */
:root {
--card-padding: 1rem;
}
.card {
padding: var(--card-padding);
}
/* Option B: default repeated inline */
.card {
padding: var(--card-padding, 1rem);
}The two options differ in important ways:
| Aspect | Declared default on `:root` | Inline fallback |
|---|---|---|
| Where the default lives | One place | Every `var()` call that repeats it |
| Visible to JavaScript | Yes, with `getComputedStyle` | No. The property still reads as empty |
| Works if the stylesheet is used out of context | Only if the `:root` rule is loaded | Yes, the rule carries its own default |
| Inherited by descendants | Yes | No. Only the declaration that contains the fallback uses it |
| Easy to change later | Change one line | Search and replace |
Use declared defaults for design tokens shared across a site, such as colors and spacing. Use inline fallbacks for optional hooks, where the component must look correct even when no one has set the property. The next section covers that case.
Fallbacks in a component API
A reusable component can promise a set of custom properties that consumers may override. The component supplies the defaults with fallbacks:
.alert {
padding: var(--alert-padding, 0.75rem 1rem);
border-radius: var(--alert-radius, 4px);
background: var(--alert-bg, #fff4e5);
color: var(--alert-fg, #5f2b00);
}
.sidebar .alert {
--alert-padding: 0.5rem;
--alert-bg: #e8f1ff;
--alert-fg: #0a2a66;
}Anyone using .alert gets sensible styling with no configuration. The .sidebar rule overrides only what it needs, and the other two hooks still use their fallbacks.
There is one inheritance trap. Custom properties inherit, so a value set on an outer element also reaches nested elements:
<div class="sidebar">
<div class="alert">Outer alert</div>
<div class="panel">
<div class="alert">Inner alert, also blue</div>
</div>
</div>Both alerts receive the .sidebar overrides here, because the .sidebar .alert selector matches any descendant alert, and the custom properties it sets are inherited again below it. That is usually intended. The problem appears when a component sets a variable on itself and then reads a variable of the same name from its parent. A common safe pattern is to read the public hook into a private variable on the component, then use the private variable:
.btn {
--_bg: var(--btn-bg, #0b5fff);
background: var(--_bg);
border: 2px solid var(--_bg);
}The fallback is written once. Later declarations use --_bg and cannot drift out of sync. The underscore is only a naming convention. CSS gives it no special meaning. It signals to other developers that the property is internal.
What a fallback does not do
The most common mistakes come from expecting the fallback to cover cases it does not cover.
It does not catch a bad value
A fallback replaces a missing custom property. It does not replace a property that exists but holds the wrong kind of value:
:root {
--size: banana;
}
.box {
width: var(--size, 100px);
}Here --size is defined, so the fallback is skipped. The browser substitutes banana into width: banana, finds that invalid, and the declaration becomes invalid at computed-value time. The width then behaves as if it had been unset. For a non-inherited property such as width, that means its initial value, auto. It does not mean 100px.
This behavior is covered fully in the chapter on substitution. For now, remember that custom properties accept almost any text. Validation happens only after substitution, when the real property checks the result.
It does not provide a cascade fallback for old browsers
Developers sometimes write a plain declaration first, expecting it to rescue them when a variable is missing:
.box {
color: blue;
color: var(--text-color);
}In a browser that does not understand var(), the second line is discarded and color: blue remains. In every current browser, the second line is accepted at parse time, and it wins the cascade even if --text-color is never defined. When the variable is missing, the declaration becomes invalid at computed-value time. The result is color inheriting from its parent, because color is an inherited property. It is not blue. If you want blue as the working default, put it inside the function:
.box {
color: var(--text-color, blue);
}It does not apply to the property you are declaring
A fallback belongs to a var() reference. It cannot supply a default for the custom property declaration itself. Writing --x: 10px on .a and then reading var(--x, 5px) on a child gives 10px through inheritance. The 5px is used only on elements where --x is not set anywhere above them.
It does not repair a broken fallback
If a fallback contains a var() that is also missing, and that inner var() has no fallback, the whole reference becomes invalid at computed-value time:
.box {
margin: var(--gap, var(--gap-fallback));
}When neither --gap nor --gap-fallback is defined, nothing supplies a value, so margin is invalid at computed-value time and falls back to its initial value, 0. Always end a chain with a concrete value unless you intend the unset behavior.
Fallbacks inside custom property declarations
A custom property can use var() with a fallback in its own value. This is how you build layered tokens:
:root {
--space-unit: 8px;
--space-card: var(--space-override, calc(var(--space-unit) * 2));
}
.compact {
--space-override: 4px;
}
.card {
padding: var(--space-card);
}There is a subtlety here. Custom properties are resolved on the element where they are declared, and the computed result is then inherited. --space-card is declared on :root, so var(--space-override, ...) is resolved against :root. Setting --space-override on .compact does not change --space-card for descendants of .compact, because they inherit the already computed value from the root.
If you want the override to take effect lower in the tree, resolve the chain on the element that needs it. The simplest way is to put the lookup in the property that uses it:
.card {
padding: var(--space-override, calc(var(--space-unit) * 2));
}This is a frequent source of "my override does nothing" bugs, and it follows directly from how scope and inheritance work.
Writing maintainable fallbacks
A few habits keep fallback chains easy to read:
- Put the fallback you want in the common case last, as a literal value. Do not leave the chain open.
- Keep chains to two levels where possible. Past that, declare a default on
:rootand refer to it. - Avoid repeating a long fallback. Read it once into a private variable, as in the
.btnexample above. - Name public hooks with the component name as a prefix, such as
--alert-bg, so they do not collide with page-level tokens. - Test a component with no custom properties set at all. If it looks broken, a fallback is missing.
Summary of the rules
| Situation | Result |
|---|---|
| Property defined with a valid value | Property value used, fallback ignored |
| Property never declared | Fallback used |
| Property set to `initial` | Fallback used |
| Property in a dependency cycle | Fallback used |
| Property defined but wrong for the final property | Fallback ignored, declaration invalid at computed-value time |
| Missing property, no fallback given | Declaration invalid at computed-value time |
| Fallback contains commas | Everything after the first comma is the fallback |
Exercise
Given :root { --gap: 12px; } and .row { margin-left: var(--gap, 4px); }, what is the margin of a .row element inside a container that sets --gap: initial;? What is it for a .row outside that container?
Show answer
Inside the container, --gap is reset to the guaranteed-invalid value, so the fallback applies and the margin is 4px. Outside the container, --gap inherits 12px from :root, so the margin is 12px and the fallback is ignored.
Exercise
A stylesheet contains .tag { padding: var(--tag-pad, 0.25rem 0.5rem); }. A page sets :root { --tag-pad: tiny; }. What padding does .tag get, and why does the fallback not help?
Show answer
--tag-pad is defined as tiny, so the fallback is skipped. The browser substitutes tiny into padding, which is not a valid padding value. The declaration becomes invalid at computed-value time, and padding takes its initial value of 0. The fallback covers only a missing property, not an invalid one.
Exercise
Rewrite border-color: var(--a, var(--b)) so that it ends in a concrete color, using --a first, then --b, then teal.
Show answer
border-color: var(--a, var(--b, teal));