Sub topic 11
Custom properties: inheritance you control
Earlier chapters showed that the cascade picks one winning declaration per property, and that inheritance fills in values the cascade leaves unset. Custom properties use both mechanisms, but you choose the names and the values. This chapter explains how they cascade and inherit, when var() is resolved, and the mistakes that follow from that timing.
It assumes you know specificity, source order, cascade layers, and the difference between inherited and non-inherited properties. You should also be able to inspect an element in browser developer tools.
What a custom property is
A custom property is a property whose name starts with two dashes. You declare it like any other property and read it with the var() function.
:root {
--brand: #0b6bcb;
--gap: 1rem;
}
.button {
background: var(--brand);
padding: var(--gap);
}Several details are easy to miss:
- Names are case-sensitive.
--Gapand--gapare two different properties. - The browser does not interpret the value of an ordinary custom property. It stores the sequence of tokens you wrote.
--gap: 1remis just the tokens1remuntil some property uses it. - Custom properties do nothing on their own. A declaration such as
--brand: redchanges no rendering until a real property reads it throughvar(). :rootmatches thehtmlelement. Declaring shared values there is a convention, not a requirement. You can declare a custom property on any element.
Custom properties inherit by default
Unlike border or margin, custom properties are inherited properties. An element that does not get its own value for --gap takes the computed value from its parent.
:root { --gap: 1rem; }
.compact { --gap: 0.25rem; }
.stack > * + * { margin-top: var(--gap); }Suppose a .stack sits inside a .compact element. The .stack has no --gap declaration, so it inherits 0.25rem from .compact. A .stack elsewhere inherits 1rem from :root. The rule that reads the variable is the same in both places. Only the value that arrives from above differs.
This is why custom properties are described as scoped to a subtree. The scope is not a block or a file. It is the element where you declare the property and all of its descendants, until a descendant declares the property again.
Custom properties go through the cascade
Declaring a custom property is subject to the same cascade as any other declaration. Within a single element, when two rules set --brand, the cascade compares them in order:
- Origin and
!important. - Cascade layers.
- Specificity.
- Source order.
.button { --accent: gray; }
.button { --accent: steelblue; }
#save { --accent: green; }For <button class="button" id="save">, the id selector has higher specificity, so --accent is green on that element. The cascade selects the winning declaration first. Inheritance applies only if no declaration for the property exists on the element.
This is useful because you can place defaults in a low-priority layer and let components override them, with no specificity fights:
@layer tokens, components;
@layer tokens {
:root { --radius: 4px; }
}
@layer components {
.card { --radius: 12px; border-radius: var(--radius); }
}When var() is resolved
The var() function is substituted at computed-value time, on the element that uses it. The browser takes the element's own computed value for the custom property, which includes anything it inherited, and puts those tokens in place of var(--name). Then it parses the result as a value for the property that contains it.
This produces a rule that matters often: a custom property that contains var() is itself resolved on the element that declares it. Descendants then inherit the resolved result, not the formula.
:root {
--gap: 1rem;
--pad: calc(var(--gap) * 2);
}
.compact { --gap: 0.25rem; }
.box { padding: var(--pad); }A .box inside .compact still has 2rem of padding. --pad was resolved on :root using --gap: 1rem, and .compact only changed --gap for itself and its descendants. Nothing re-evaluates --pad there. Two fixes work:
/* Option 1: use the formula where it is needed */
.box { padding: calc(var(--gap) * 2); }
/* Option 2: redeclare the derived property wherever the input can change */
:root, .compact { --pad: calc(var(--gap) * 2); }Option 1 is simpler and is usually the better choice. Option 2 is useful when many rules share the derived value.
Fallback values
var() accepts a second argument, used when the property is not defined on the element.
.button {
color: var(--button-color, white);
border-radius: var(--button-radius, var(--radius, 4px));
}- Everything after the first comma is the fallback, including later commas.
var(--font, Helvetica, Arial, sans-serif)falls back to the whole listHelvetica, Arial, sans-serif. - The fallback can itself contain
var(), as in the nested example above. - The fallback is used only if the property is missing or holds the guaranteed-invalid value (explained below). A defined but unhelpful value, such as
--button-color: banana, is not replaced by the fallback.
Fallbacks let a component work with no theme and still accept configuration from an ancestor. This is a common way to build a component API: the component reads --button-color and the page decides whether to set it.
Invalid at computed-value time
If var() has no usable value and no fallback, the declaration does not get ignored the way an invalid declaration would at parse time. Parsing already succeeded, because the browser cannot know what var() will produce. The declaration is instead treated as invalid at computed-value time, and the property behaves as if it were set to unset. That means it inherits if the property is inherited, and takes its initial value if not.
p {
color: red;
color: var(--missing);
}
.panel {
border-width: 5px;
border-width: var(--missing);
}The paragraph is not red. The second declaration wins the cascade, then fails to resolve, so color (an inherited property) takes the parent's color. The panel's border width is not 5px either. border-width is not inherited, so it goes to its initial value, medium. Writing an earlier valid declaration as a safety net does not work with var(). Use a fallback inside var() instead.
The same outcome applies to cycles. If --a: var(--b) and --b: var(--a), both properties are invalid and any property using them is treated as unset.
CSS-wide keywords on custom properties
The keywords from the previous chapter also work on custom properties, with one twist.
| Declaration | Effect on the custom property |
|---|---|
| `--x: inherit` | Takes the parent's value. It is already the default, so this is rarely needed. |
| `--x: initial` | Sets it to the guaranteed-invalid value, meaning "not defined". |
| `--x: unset` | Same as `inherit`, because custom properties are inherited. |
The initial keyword is the useful one. An unregistered custom property has no real initial value, so initial gives you the guaranteed-invalid value. The effect is that fallbacks start working again:
:root { --accent: orange; }
.plain {
--accent: initial;
color: var(--accent, black);
}The .plain element, and its descendants through inheritance, see --accent as undefined and use the fallback black. You have cut the inherited value off for that subtree.
Controlling inheritance with @property
Sometimes you want a custom property that does not pass down. The @property at-rule registers a custom property with a type, an initial value, and an explicit inheritance setting.
@property --card-pad {
syntax: "<length>";
inherits: false;
initial-value: 1rem;
}
.card {
padding: var(--card-pad);
}
.card.tight {
--card-pad: 0.25rem;
}A card nested inside a .tight card does not inherit 0.25rem. It gets the registered initial value, 1rem. This keeps a component's local setting from leaking into nested components of the same kind.
Registration also changes timing. A registered property with a <length> syntax is computed on the element that declares it. An unregistered --size: 2em passes the tokens 2em down, and each user resolves them against its own font size. A registered --size resolves to an absolute length such as 32px on the declaring element and passes that down. Registration also lets browsers animate the property, and it gives invalid values a defined behavior: an assignment that does not match the syntax is rejected at parse time.
Support for @property is in all current major browsers, but check your support targets before you rely on it.
A worked example: theme tokens
This example puts the pieces together. A page defines a light theme at the root, switches to dark for a subtree, and exposes one component-level setting.
@layer tokens, components;
@layer tokens {
:root {
--surface: #ffffff;
--text: #1a1a1a;
--accent: #0b6bcb;
}
[data-theme="dark"] {
--surface: #14181f;
--text: #f2f4f8;
--accent: #6cb2ff;
}
}
@layer components {
body {
background: var(--surface);
color: var(--text);
}
.panel {
background: var(--surface);
color: var(--text);
border: 1px solid var(--accent);
padding: var(--panel-pad, 1rem);
}
}<body>
<div class="panel">Light panel</div>
<section data-theme="dark">
<div class="panel" style="--panel-pad: 2rem">Dark panel</div>
</section>
</body>Both panels use the same .panel rule. The first inherits the light tokens from :root. The second sits under data-theme="dark", so it inherits the dark tokens. The inline style sets --panel-pad on that element only, which beats the 1rem fallback. The [data-theme="dark"] rule has higher specificity than :root, but that does not matter here, because the two rules match different elements. Cascade comparison happens per element. For an element matched by both, the more specific selector would win.
Note that <section data-theme="dark"> itself has no background. If you want the section to look dark, give it background: var(--surface) too, as the body rule does.
Debugging custom properties
Use the browser's developer tools for the same checks you would run on any property:
- Select the element and open the Styles panel. Find the declaration that uses
var(--name). Hovering over the variable name or its resolved swatch usually shows the value in effect. - Check whether the rule declaring
--nameappears crossed out. A crossed-out declaration lost the cascade, and the rule that beat it is listed above it. - If the property using
var()is crossed out or shows a warning, the variable may be undefined or invalid on that element. Look at the parent's Styles panel to see whether it was ever declared on an ancestor. - Open the Computed panel to see the final value of the real property. If it shows the inherited or initial value instead of what you expected, you are probably seeing invalid at computed-value time.
Common causes, in rough order of frequency: a typo or case mismatch in the name, the variable declared on a sibling or descendant instead of an ancestor, a derived variable resolved too high in the tree, and a layer that sets a competing value.
Summary of the model
- Custom properties are declared with
--name, compared in the cascade like other properties, and inherited by default. var()is substituted on the element that uses it, at computed-value time.- A custom property containing
var()is resolved where it is declared, and descendants inherit the result. - Missing values with no fallback make the using property
unset. initialmakes a custom property undefined, and@propertywithinherits: falsestops it from passing down.
Exercise
Given this CSS, what is the padding of a .box inside a .wide element, and why?
:root { --unit: 4px; --space: calc(var(--unit) * 4); }
.wide { --unit: 10px; }
.box { padding: var(--space); }
How would you change the CSS so the box inside .wide gets 40px?
Show answer
The padding is 16px. --space is resolved on :root using --unit: 4px, giving 16px, and descendants inherit that resolved value. Changing --unit on .wide does not re-evaluate --space. To get 40px, either write .box { padding: calc(var(--unit) * 4); } or redeclare the derived property with :root, .wide { --space: calc(var(--unit) * 4); }.
Exercise
A paragraph has color: blue; color: var(--text-color); and no ancestor defines --text-color. The body has color: #222. What color is the paragraph text, and what single change makes it blue?
Show answer
The text is #222. The second declaration is valid at parse time, but at computed-value time the variable is missing, so color behaves as unset. Because color is inherited, it takes the parent's value. Adding a fallback, color: var(--text-color, blue), makes the text blue when the variable is missing.
Exercise
You build a .card that reads --card-pad. A .card.tight sets --card-pad: 0.25rem, and cards can be nested. How do you stop nested cards from inheriting the tight padding, and which at-rule do you use?
Show answer
Register the property with @property --card-pad { syntax: "<length>"; inherits: false; initial-value: 1rem; }. With inherits: false, a nested card does not receive the parent's value and uses the initial value, 1rem, unless it sets its own.