Sub topic 4
How var() substitution works and what happens with invalid values
This chapter assumes you can declare a custom property, read it with var(), and write a fallback. It also assumes you know the basics of the cascade and inheritance. Here you will learn what the browser does with var() internally, which explains most of the confusing behavior people hit with custom properties.
Two moments: parse time and computed-value time
A browser handles a CSS declaration in stages. Two of them matter for var():
- Parse time. The browser reads the stylesheet and decides whether each declaration is valid. An invalid declaration is dropped, as if you had never written it.
- Computed-value time. The browser works out each element's cascaded values and turns them into computed values. This is when
var()is replaced.
Ordinary declarations are checked at parse time. A declaration that contains var() cannot be checked then, because the browser does not yet know what the custom property will contain. So it accepts the declaration as long as the syntax around var() is well formed. It checks the real value later, once substitution has happened.
p {
color: green;
color: 12px;
}The second declaration is invalid for color. The browser drops it at parse time, so green stays in the cascade.
:root {
--size: 12px;
}
p {
color: green;
color: var(--size);
}The second declaration passes parse time, because var() hides its content. It also wins the cascade, because it comes later. Only at computed-value time does the browser find that color: 12px makes no sense. The earlier green is not restored. This is the main difference between the two cases.
Substitution works on tokens
A custom property stores a sequence of CSS tokens. The browser does not check whether the sequence is a color, a length, or anything else. All of these are valid custom property values:
:root {
--a: 8px;
--b: 1px solid red;
--c: Helvetica, Arial, sans-serif;
--d: { not: "a real value" };
}When var(--b) appears in a declaration, the browser replaces it with those tokens. Then it parses the whole declaration as though you had typed the tokens yourself.
.box {
border: var(--b);
}After substitution this is border: 1px solid red, which is valid. The same property used somewhere else gives a different outcome:
.box {
width: var(--b);
}After substitution this is width: 1px solid red. The declaration is not valid for width, so it is invalid at computed-value time.
Because substitution happens on tokens, you can store pieces of a value and combine them:
:root {
--h: 210;
--s: 80%;
--l: 45%;
}
.badge {
background: hsl(var(--h) var(--s) var(--l));
}Each variable supplies one component, and hsl() receives the final token list.
A unit pitfall
A stored number and a unit written beside var() do not merge into one token.
:root {
--n: 8;
}
.bad {
padding: var(--n)px;
}
.good {
padding: calc(var(--n) * 1px);
}.bad produces the tokens 8 and px as separate pieces, which is not a length, so it is invalid at computed-value time. .good multiplies a number by a length, which gives a valid length. When a variable holds a bare number, convert it with calc(). Alternatively, store the unit in the variable.
Invalid at computed-value time
When substitution produces something the property cannot accept, the declaration is invalid at computed-value time. You will often see this shortened to IACVT. The browser then treats the property as if its value were unset:
- For an inherited property such as
colororfont-family, the element inherits the parent's value. - For a non-inherited property such as
background-colororpadding, the element gets the property's initial value.
This runs the example from earlier to its end:
<!DOCTYPE html>
<html>
<head>
<style>
:root { --size: 12px; }
body { color: blue; }
p {
color: green;
color: var(--size);
background-color: yellow;
background-color: var(--size);
}
</style>
</head>
<body>
<p id="demo">Sample</p>
<script>
const style = getComputedStyle(document.getElementById('demo'));
console.log(style.color); // rgb(0, 0, 255)
console.log(style.backgroundColor); // rgba(0, 0, 0, 0)
</script>
</body>
</html>color is inherited, so it falls back to the parent's blue, not to the green written just above it. background-color is not inherited, so it becomes transparent, not yellow.
Where to look when this happens
Browser developer tools mark these declarations. In Chrome and Firefox, the Styles panel shows the declaration with a warning icon and a note that it is invalid at computed-value time. The Computed panel shows the value the property actually received. If an element looks unstyled and the rule seems to match, check for this note first.
The guaranteed-invalid value and fallbacks
An unregistered custom property that nobody has set does not hold an empty string. It holds a special value called the guaranteed-invalid value. It is the initial value of every custom property. When var() refers to a property holding this value, the fallback is used. If no fallback exists, the declaration is invalid at computed-value time.
The fallback is only consulted in that situation. It is not used when the custom property has a value that happens to be wrong for the place you use it.
:root {
--gap: red;
}
.row {
margin-left: var(--gap, 10px);
}--gap exists, so the fallback 10px is ignored. The result is margin-left: red, which is invalid at computed-value time, and margin-left becomes its initial value, 0. The fallback does not rescue it.
Fallback syntax details
- The browser splits
var()at the first comma only. Everything after it, commas included, belongs to the fallback. - A fallback can contain another
var(), so you can chain several levels. - A fallback can be empty:
var(--x,).
.text {
font-family: var(--font, Helvetica, Arial, sans-serif);
border-color: var(--edge, var(--brand, gray));
}In the first line, the fallback is the whole list Helvetica, Arial, sans-serif. In the second line, the browser tries --edge, then --brand, then gray.
Resetting a property and empty values
You can put a custom property back to the guaranteed-invalid value with the CSS-wide keywords. --gap: initial does that on any element, which makes fallbacks apply again. This is useful when a child must ignore a value set by an ancestor.
An empty value is different. --gap: ; is a valid declaration in current browsers, and it sets the property to an empty token list. That is a real value, so fallbacks are not used. Substituting it into margin-left: var(--gap, 10px) yields margin-left: with nothing after it, which is invalid at computed-value time.
| Custom property state | `var(--x, 10px)` gives | Why |
|---|---|---|
| Never declared | `10px` | Guaranteed-invalid value, fallback used |
| `--x: initial;` | `10px` | Reset to guaranteed-invalid |
| `--x: ;` (empty) | Empty, so usually invalid | An empty value is a real value |
| `--x: red;` used in `margin` | Invalid at computed-value time | `red` is a real value, the fallback is skipped |
| `--x: 4px;` used in `margin` | `4px` | Valid result |
When substitution happens for custom properties
A custom property can refer to another custom property:
:root {
--space: 8px;
--gap: calc(var(--space) * 2);
}Substitution inside a custom property also happens at computed-value time, but on the element where the property is declared. The child elements then inherit the already-substituted result of --gap, not the formula.
:root {
--space: 8px;
--gap: calc(var(--space) * 2);
}
.compact {
--space: 4px;
}
.row {
margin-bottom: var(--gap);
}An element .row inside .compact still gets 16px. On :root, --gap was computed as calc(8px * 2) and inherited in that form. Changing --space on .compact does not recompute it.
There are two ways to get the expected 8px:
- Redeclare
--gapin.compact, so it is substituted there with the new--space. - Put the
calc()where the value is used:margin-bottom: calc(var(--space) * 2). Substitution then runs on the element that uses it, which sees the local--space.
Cycles
If custom properties depend on each other in a loop, no value can be computed. Every property in the cycle becomes the guaranteed-invalid value.
:root {
--a: var(--b);
--b: var(--a);
--self: var(--self);
}
.item {
color: var(--a, purple);
outline-color: var(--self, orange);
}All three properties are in cycles, so they hold the guaranteed-invalid value, and the fallbacks purple and orange apply. Without a fallback, the declarations would be invalid at computed-value time. A cycle is a common result of a refactor in which --color: var(--color) appears by mistake.
A custom property can still be defined in terms of itself from a parent scope in a way that is not a cycle, by reading the inherited value and redeclaring it. In practice this is rarely possible, because var(--x) on --x is always a self-reference on that element. Pick a different name for the derived value.
Checking values with a script
You can see what the browser decided by reading the computed style. For a custom property, getPropertyValue returns the substituted token text. For a normal property, it returns the final computed value.
const el = document.querySelector('.row');
const style = getComputedStyle(el);
console.log(style.getPropertyValue('--gap').trim());
console.log(style.marginBottom);CSS.supports is a quick way to test whether a token string is valid for a property. It tests ordinary values, so use it with concrete text, not with var():
console.log(CSS.supports('margin-left', '10px')); // true
console.log(CSS.supports('margin-left', 'red')); // false
console.log(CSS.supports('color', 'var(--anything)')); // trueThe last line is true for the reason from the start of the chapter. A value with var() always passes the parse-time check.
Common mistakes
- Expecting a fallback to fix a wrong value. Fallbacks cover only a missing value.
- Writing
var(--n)px. Usecalc(var(--n) * 1px). - Expecting an earlier declaration to survive. After IACVT, the property is
unset. - Expecting a derived custom property to follow a local override of its inputs.
- Declaring the property name with a typo.
--brnad-coloris a valid custom property that nobody reads, andvar(--brand-color)then has nothing to substitute. Custom property names are case-sensitive, so--Brandand--brandare different. - Putting a stray semicolon or brace inside a value. The brace form in the earlier
--dexample is legal, but it will not substitute into any normal property.
Exercises
Exercise
A rule contains padding: 4px; padding: var(--pad); and --pad: red; is set on :root. What is the computed padding, and why?
Show answer
The computed padding is 0. The var() declaration passes parse time and wins the cascade. After substitution, padding: red is invalid, so the declaration is invalid at computed-value time. Padding is not inherited, so it behaves as initial, which is 0. The earlier 4px is not used.
Exercise
--x is never declared. What does width: var(--x, 50%) give? What changes if you add --x: ; on :root?
Show answer
With --x undeclared, the property holds the guaranteed-invalid value, so the fallback applies and width is 50%. With --x: ; on :root, the property holds an empty value. That is a real value, so the fallback is not used. The declaration becomes width: with nothing after it, which is invalid at computed-value time, and width gets its initial value auto.
Exercise
Given :root { --space: 8px; --gap: calc(var(--space) * 2); } and .tight { --space: 2px; }, what is --gap inside .tight? Give two ways to make it 4px.
Show answer
It is still 16px, because --gap was substituted on :root and children inherit the result. One fix is to redeclare --gap: calc(var(--space) * 2); in .tight. The other is to write calc(var(--space) * 2) directly in the declaration that uses the value, so substitution happens on the element with the local --space.