Sub topic 11
Limitations and common pitfalls
This chapter assumes you can declare custom properties, read them with var(), and explain how they inherit. It also assumes you have used calc() and know the basics of getComputedStyle. Custom properties look like ordinary variables, but the browser handles them differently from variables in a programming language. Most surprises come from that difference.
Custom properties are token streams, not typed values
An unregistered custom property stores a sequence of tokens. The browser does not check that --gap: 8px is a length, and --gap: banana is equally valid. Validation happens later, when var() substitutes the tokens into a real property and the browser parses the result.
This has three consequences:
- Typos in values are not reported where you declare them.
- Units and numbers are separate tokens until substitution.
- Relative units resolve where the value is used, not where it is declared.
Gluing a unit onto a number fails
:root {
--space: 8;
}
.broken {
padding: var(--space)px;
}
.works {
padding: calc(var(--space) * 1px);
}After substitution, .broken becomes the tokens 8 and px side by side. They do not form a dimension such as 8px, so the declaration is invalid. Store the full value (--space: 8px), or multiply a unitless number by 1px inside calc().
Relative units resolve at the point of use
:root {
font-size: 20px;
--pad: 2em;
}
.small {
font-size: 10px;
padding: var(--pad);
}Many people expect .small to get 40px of padding, from 2em at the root. It gets 20px, because 2em is substituted into .small and resolved against .small's own font size. Registering the property with a type changes this, as shown later in this chapter.
Invalid at computed-value time
This is the most confusing rule. The browser can only check a declaration containing var() after it knows the custom property's value. If the substituted result is not valid for that property, the declaration becomes invalid at computed-value time.
The important part is what happens next. The declaration does not disappear, and the cascade does not fall back to an earlier rule. The property behaves as if you had written unset:
- Inherited properties, such as
color, take the parent's value. - Non-inherited properties, such as
background, take their initial value.
.box {
background: red;
background: var(--missing);
}If --missing is not defined, .box gets a transparent background, which is the initial value. It does not get red. The older "write a plain value first as a fallback" trick only helps browsers that do not understand var() at all. It does nothing when a variable is undefined or wrong.
.title {
--size: 2rem;
color: var(--size);
}Here --size is defined, but 2rem is not a color. color is inherited, so .title quietly uses its parent's color. Nothing is reported as an error. If a property has no visible effect, open DevTools. Most browsers mark the declaration as invalid at computed-value time there.
The diagram shows that a fallback only covers an undefined property. A fallback does not rescue a defined property whose value has the wrong type. It also shows that an invalid fallback leads to the same dead end.
Cycles
If two custom properties refer to each other, both become invalid.
:root {
--a: var(--b);
--b: var(--a);
}
.demo {
color: var(--a, red);
}A dependency cycle makes every property in it the guaranteed-invalid value, which is what an undefined property has. In .demo, --a counts as undefined, so the fallback red applies. A property that refers to itself, such as --x: calc(var(--x) + 1), is also a cycle. You cannot build counters this way. If you want to extend a value, give the new one a different name, for example --space-lg: calc(var(--space) * 2).
Where var() cannot be used
var() can only replace the value of a property. It cannot appear in these places:
| Place | Example that fails | What to do instead |
|---|---|---|
| Property names | `var(--prop): red` | Write the property name literally. |
| Selectors | `.var(--name) { }` | Use classes or attributes. |
| Media query conditions | `@media (min-width: var(--bp))` | Write the number, or redefine properties inside the query. |
| Part of a `url()` with an unquoted argument | `url(var(--path)/a.png)` | Store the whole `url("...")` in the variable. |
| Unit suffixes | `var(--n)px` | `calc(var(--n) * 1px)` |
Media queries
Media query conditions are evaluated before any element is styled, so there is no element to inherit variables from. :root variables do not apply either. A common workaround is to repeat the breakpoint literal, and to vary the property values inside the query instead of the condition:
:root {
--columns: 1;
}
@media (min-width: 48rem) {
:root {
--columns: 2;
}
}
.grid {
display: grid;
grid-template-columns: repeat(var(--columns), 1fr);
}If you need one source of truth for breakpoints, use a preprocessor or a build step that inserts the number. Container style queries, such as @container style(--theme: dark), can test a custom property's value, but browser support has varied. Check current support before relying on them.
url()
A variable can hold a complete url(). For example, --hero: url("/img/hero.jpg") works with background-image: var(--hero). Be careful with relative paths. In some browsers they resolve against the stylesheet where the property is used, not where it was declared, so prefer root-relative or absolute paths in shared variables.
Fallback syntax details
Only the first comma separates the variable name from the fallback. Everything after it is the fallback, commas included:
body {
font-family: var(--font, Helvetica, Arial, sans-serif);
}Two related points:
- A custom property set to an empty value (
--x:;) is defined. It substitutes an empty token stream, which usually makes the declaration invalid. It does not trigger the fallback. - Setting
--x: initialresets the property to the guaranteed-invalid value. That makes it undefined again, so fallbacks apply. Use this to "unset" a variable that a parent defined.
Names are case-sensitive. --Brand and --brand are different properties, and a mismatch silently produces an undefined variable.
Inheritance surprises
Custom properties inherit by default, which is usually what you want. It also means a value set on a wrapper reaches every descendant, including nested components that you did not expect to be affected.
.btn {
--btn-bg: royalblue;
background: var(--btn-bg);
}
.toolbar {
--btn-bg: gray;
}The .toolbar rule does nothing for .btn elements inside it. .btn sets --btn-bg on itself, and a value set directly on an element wins over an inherited one. Hooks that outside code should override must not be set on the component's own selector. Read them with a fallback instead:
.btn {
background: var(--btn-bg, royalblue);
}Now .toolbar { --btn-bg: gray; } changes every button inside it. This is the difference between a private variable and a public hook.
The reverse problem is leakage. A component's internal custom property, such as --card-padding, inherits into nested cards. A card inside a card sees the outer value unless the inner one sets its own. When you nest components, set each internal variable on the component's own root selector, and expose only the hooks you intend.
Registered properties change the rules
Registering a property with @property gives it a type, a default, and an inheritance setting. That fixes several of the problems above.
@property --pad {
syntax: '<length>';
inherits: true;
initial-value: 0px;
}
:root {
font-size: 20px;
--pad: 2em;
}
.small {
font-size: 10px;
padding: var(--pad);
}With a <length> type, the value computes to 40px at :root and that computed length is inherited. .small gets 40px padding. Registration also validates the value: assigning --pad: banana is discarded at parse time, and the property falls back to its initial value, so a bad value cannot reach your other declarations.
Watch for these gotchas:
initial-valuemust be computationally independent.0pxworks.2emandvar(--x)do not, and the whole registration is ignored.inheritsis required. Registering without it invalidates the rule.- A name can be registered only once. A repeated
@propertyrule with the same name is ignored, and the last valid registration wins in some situations, so keep registrations in one stylesheet. - A registered property no longer behaves as "undefined" when unset. It always has at least its initial value, so
var(--x, fallback)never uses the fallback.
That last point is easy to miss. If you register --accent with an initial-value, every var(--accent, red) in your code now resolves to the initial value, and the red is dead code.
Animation and transitions
Unregistered custom properties are not interpolated. If you put transition: --angle 0.4s on an element, the value switches at once. Two ways to get smooth results:
- Register the property with a suitable
syntax, such as<angle>,<length>, or<color>, and transition it directly. - Transition the real property that uses the variable. If
background: var(--bg)is present and--bgchanges, the computedbackgroundchanges, andtransition: background 0.3sanimates it as usual.
Registered properties also let you animate things that CSS cannot normally animate, such as gradient stops. The registration is what makes it possible. The type tells the browser how to interpolate.
JavaScript pitfalls
Reading values is where most trouble shows up.
function readVar(element, name) {
return getComputedStyle(element).getPropertyValue(name).trim();
}
const root = document.documentElement;
root.style.setProperty('--brand-color', '#e91e63');
console.log(readVar(root, '--brand-color'));
console.log(readVar(root, '--not-defined') === '');getPropertyValueon an unregistered custom property returns the raw text, often with leading whitespace. Call.trim().- An undefined property gives an empty string, not
nulland notundefined. Compare against''. element.style.getPropertyValue('--x')reads only inline styles. It misses values from stylesheets and inherited values. UsegetComputedStylefor the effective value.- The returned string is not converted. For
--size: 2em, you get"2em", not pixels. If you need a number, register the property with a type, or measure a real property such asgetComputedStyle(el).paddingLeft. - Names passed to
setPropertyneed the leading dashes. WritingsetProperty('brand-color', ...)does nothing useful. Also,root.style['--brand-color']does not work, so use the method. - Setting a shorthand with
var()in it, for exampleel.style.margin = 'var(--space)', leaves the longhands such asmarginTopreading as an empty string. The browser cannot split the value until substitution occurs.
Performance
Changing a custom property forces the browser to recompute styles for every element that inherits it. Updating --mouse-x on :root for each pointer move recalculates the whole document. Set the variable on the smallest element that needs it instead:
const card = document.querySelector('.card');
card.addEventListener('pointermove', (event) => {
const box = card.getBoundingClientRect();
card.style.setProperty('--x', `${event.clientX - box.left}px`);
card.style.setProperty('--y', `${event.clientY - box.top}px`);
});Only .card and its descendants are affected. Avoid hundreds of custom properties on :root that change often. Stable design tokens there are fine.
A debugging checklist
When a variable "does not work", check these in order:
- Is the name spelled the same, with the same case, in the declaration and the use?
- Is the property defined on the element or an ancestor? Look at the Computed pane for the custom property.
- Is the substituted value valid for the property that uses it? Look for "invalid at computed-value time" markers.
- Does a closer element redefine the variable? A value set directly on an element beats an inherited one.
- Is the fallback unreachable because the property is registered or set to an empty value?
- Are you trying to use
var()in a media query, selector, or property name?
Exercise
A stylesheet contains .alert { border: 1px solid red; border: 1px solid var(--alert-color); }, and --alert-color is never defined. What border does .alert get, and why? How would you make it red when the variable is missing?
Show answer
The border is not red. The second declaration wins in the cascade, and it is invalid at computed-value time because --alert-color is undefined. The browser then treats border-color as unset, so border-color takes currentcolor, the element's text color, and the 1px solid parts remain. Add a fallback inside var(), as in border: 1px solid var(--alert-color, red);. The earlier plain declaration does not act as a fallback for an undefined variable.
Exercise
You declare :root { --gap: 4; } and write margin: var(--gap)px;. The margin has no effect. Give two valid fixes.
Show answer
After substitution the tokens are 4 and px, which do not combine into a dimension. Fix one: store the unit in the variable, --gap: 4px;, and use margin: var(--gap);. Fix two: keep the number unitless and write margin: calc(var(--gap) * 1px);.
Exercise
A registered property --accent has initial-value: blue. A rule says color: var(--accent, red); and no element ever sets --accent. What color results, and why?
Show answer
Blue. A registered property always has a value, at least its initial value, so it is never undefined and the fallback red is never used.