Custom Properties: Variables, Fallbacks, Scope and Changing Them at Runtime
CSS variables in depth: declaring custom properties and using var(), fallbacks, how they cascade and inherit, theming by redefining them, invalid at computed-value time, token substitution, where var() can't go, and setting them from JavaScript.
kvi5hnuCode Sprout team member9 min readOn this page
Custom properties, often called CSS variables, let you store a value once and use it in many places. Unlike variables in preprocessors such as Sass, they're real properties: they cascade, inherit, can change inside a part of the page, and can be updated at runtime by media queries, states or JavaScript. That makes them the basis of theming, design tokens and configurable components.
Declaring and using them
A custom property is any property whose name starts with two hyphens. You read it with var():
:root {
--brand: #8a3b12;
--surface: #f4efe6;
--space: 1rem;
--font-body: "Source Sans 3", system-ui, sans-serif;
}
body { font-family: var(--font-body); background: var(--surface); }
.button { background: var(--brand); padding: calc(var(--space) / 2) var(--space); }
:rootmatches the<html>element, so values declared there are available everywhere through inheritance.- Names are case-sensitive.
--Brandand--brandare two different properties. - Choose names for their role, not their value.
--brandor--color-dangerstays meaningful when the color changes;--dark-reddoesn't. - A custom property can hold almost anything: a color, a length, a list of fonts, several values (
--shadow: 0 1px 2px #0003, 0 4px 12px #0002), even half a declaration. The value isn't checked until it's used.
Fallbacks
var() takes an optional fallback, used when the property isn't defined:
.card { padding: var(--card-padding, 1.25rem); }
.popup { color: var(--popup-color, var(--brand, maroon)); } /* fallbacks can nest */
.label { font-family: var(--label-font, Georgia, serif); } /* everything after the first comma */
The fallback is everything after the first comma, commas included, so Georgia, serif is one fallback. To chain properties, nest var() calls; var(--a, --b) uses the literal text --b, not the property.
Fallbacks are used when the property is undefined, set to initial, or part of a dependency cycle (--a: var(--b); --b: var(--a)). They're not used when the value is defined but wrong for the property. That case is explained below.
Fallbacks are good for component defaults: a component reads var(--card-padding, 1.25rem), and pages can override --card-padding without touching the component's CSS.
They cascade and inherit
Custom properties are ordinary properties in the cascade: the usual rules of specificity, layers and source order pick a value for each element, and the value inherits to descendants. Redefining a property on an element changes it for everything inside:
:root { --panel-bg: #ffffff; --panel-text: #2b2118; --panel-accent: #8a3b12; }
.dark { --panel-bg: #2b2118; --panel-text: #f4efe6; --panel-accent: #f4c95d;
background: #45362a; padding: 1rem; border-radius: 10px; margin-top: 1rem; }
body { font-family: system-ui, sans-serif; background: #f4efe6; }
.panel { background: var(--panel-bg); color: var(--panel-text);
border: 1px solid color-mix(in srgb, var(--panel-text) 25%, transparent);
border-radius: 8px; padding: 0.75rem 1rem; }
.panel h3 { color: var(--panel-accent); margin: 0 0 0.25rem; }
.panel p { margin: 0; }
The panel's CSS doesn't change; only the variables do. That's how themes, dark mode and component variants usually work:
:root { --bg: #fff; --text: #1d1a17; }
@media (prefers-color-scheme: dark) { :root { --bg: #1d1a17; --text: #f4efe6; } }
.button { --button-bg: var(--brand); background: var(--button-bg); }
.button.danger { --button-bg: #b42318; }
.button:hover { --button-bg: color-mix(in srgb, var(--brand), black 15%); }
Because a variable resolves on each element, a value defined in terms of another variable resolves where it's declared. :root { --text-muted: color-mix(in srgb, var(--text) 60%, transparent); } computes once on the root, so redefining --text in .dark doesn't change --text-muted there. To make derived values follow local overrides, declare them on the elements that use them, or on *.

On the left, the dark card inherits a --text-muted that was already computed from the light theme's dark text, so the muted line disappears into the background.
Invalid at computed-value time
Browsers can't check a var() value when they parse the stylesheet, because the variable could be anything. They check it when they compute the style. If the substituted value is invalid for the property, the declaration doesn't get thrown away the way an ordinary invalid declaration would. It becomes invalid at computed-value time, and the property behaves like unset: inherited properties inherit, and others get their initial value.
:root { --gap: 5vw; }
p { color: red; }
p { color: var(--gap, blue); } /* a length isn't a color */
The paragraph is not red and not blue. The fallback isn't used, because --gap is defined, and the earlier color: red is already discarded, because the cascade chose this declaration. So color inherits from the parent. The same thing happens to margin-left: var(--brand): it becomes 0.
This is the most common source of "my variable doesn't work" confusion. To get type checking, a real initial value and better error handling, register the property with @property (article 28).
Token substitution
var() substitutes the tokens of the value, as if they were typed in its place. It doesn't evaluate them first:
.a { --sum: 1 + 2; z-index: calc(var(--sum) * 2); } /* calc(1 + 2 * 2) = 5, not 6 */
.b { --sum: (1 + 2); z-index: calc(var(--sum) * 2); } /* 6 */
.c { --n: 40; width: var(--n)px; } /* invalid: "40 px", two tokens */
.d { --n: 40; width: calc(var(--n) * 1px); } /* 40px */
- Wrap expressions in parentheses, or
calc(), when you store them. - To add a unit, multiply by one unit. You can't join a number and a unit by writing them next to each other.

None of these declarations is dropped at parse time. Each one fails, or computes something unexpected, only after the variable is substituted.
Where var() can't go
var() works in property values only:
- Not in property names or selectors:
var(--side)-margin: 0and.var(--name)are invalid. - Not in media query conditions:
@media (width >= var(--bp))doesn't work, because media queries are evaluated without a specific element. Design tools and build steps usually handle shared breakpoints. Container style queries can test custom properties (article 79). - Not inside
url():url(var(--image))is invalid. Store the wholeurl("hero.jpg")in the property instead.
Empty values and toggles
A custom property can be empty (--x: ;). An empty property is defined, and substitutes nothing. Combined with initial, which makes var() use its fallback, that allows on and off switches, known as the space toggle trick:
.card { --featured: initial; } /* off: guaranteed-invalid */
.card.is-featured { --featured: ; } /* on: empty, so var() inserts nothing */
.card { border: var(--featured) 2px solid #f4c95d; } /* invalid when off, so no border */
The trick works, but it's hard to read. Style queries (article 79) and if() (article 30) now express conditions directly.
Changing them with JavaScript
Custom properties connect CSS with JavaScript. Setting one property updates every rule that uses it:
:root { --hue: 25; }
body { font-family: system-ui, sans-serif; }
.swatch { height: 4rem; border-radius: 8px; margin-top: 0.75rem;
background: oklch(0.6 0.15 var(--hue)); }
.swatch + .swatch { background: oklch(0.85 0.08 var(--hue)); }
const root = document.documentElement;
root.style.setProperty("--hue", "200"); // set
getComputedStyle(root).getPropertyValue("--hue"); // read: "200"
root.style.removeProperty("--hue"); // remove
element.style.setProperty("--x", `${event.clientX}px`); // per element
Values are strings. Use setProperty(): element.style["--hue"] = ... doesn't work, because custom properties aren't JavaScript properties of the style object. Setting a property on :root makes the browser recompute the styles of everything that inherits it, which is usually fast, but for values that change every frame, such as pointer positions, set them on the smallest element that needs them.
Custom properties and animation
An unregistered custom property has no type, so the browser can't interpolate it: a transition on --hue doesn't run at all: the value changes at once (with transition-behavior: allow-discrete, it flips at the halfway point instead), and a @keyframes animation flips at the halfway point. The properties that use the variable animate normally if their own type allows it. To animate the variable itself, give it a type with @property (article 28).
Good practice
- Define global tokens on
:root(colors, spacing, fonts) and component properties on the component (--button-bg), with page-level tokens as their defaults. - Prefix component properties with the component's name to avoid collisions:
--card-padding, not--padding. - Use fallbacks for optional settings, and
@propertyfor values that need a type. - Don't store values that never change and are used once: a variable adds a level of indirection.
What's current
- Custom properties have been in every browser since 2017.
@property(article 28) adds types, initial values and non-inheritance, and is Baseline since July 2024.- Style queries (article 79) and
if()(article 30) can branch on custom property values.
Common questions
Why isn't my fallback used?
The fallback is only for an undefined, initial or cyclic property. If the property is defined but its value is invalid for the property you use it in, the declaration becomes invalid at computed-value time and acts like unset instead.
What's the difference between CSS variables and Sass variables? Sass variables are replaced with values when the stylesheet is compiled. CSS custom properties exist in the browser: they inherit, change per element, react to media queries and states, and can be set from JavaScript.
Why does width: var(--n)px not work?
var() substitutes tokens, so the result is the number 40 followed by an unrelated px token, not 40px. Use calc(var(--n) * 1px).
Can I use a custom property in a media query?
Not in its condition. Media queries don't belong to an element, so there's nothing to resolve var() against.
Do custom properties inherit?
Yes, always, unless they're registered with @property and inherits: false.
Summary
- Custom properties start with
--, are case-sensitive, and are read withvar(). var(--x, fallback)uses the fallback when--xis undefined,initialor cyclic. Everything after the first comma is the fallback.- They cascade and inherit, so redefining them in a part of the page themes everything there.
- A substituted value that's invalid for the property makes the declaration invalid at computed-value time: it acts like
unset, without using the fallback. var()substitutes tokens. Wrap stored expressions in parentheses and multiply by1pxto add units.var()doesn't work in property names, selectors, media query conditions orurl().- JavaScript uses
style.setProperty()andgetPropertyValue(). Unregistered properties don't animate smoothly.
Practice questions
What color is the paragraph?
:root { --size: 2rem; }
div { color: green; }
p { color: orange; }
p { color: var(--size, purple); }
<div><p>Text</p></div>
Answer
Green. --size is defined, so the fallback purple isn't used. Its value isn't a color, so the declaration is invalid at computed-value time, and color acts like unset: it inherits green from the <div>. The orange declaration lost the cascade and is gone.
What does margin compute to here, and how do you fix it?
.box {
--gap: 4 + 4;
margin: calc(var(--gap) * 2px);
}
Answer
calc(4 + 4 * 2px) is invalid, since it adds a number to a length, so the margin is unset, which gives 0. Write --gap: (4 + 4) and calc(var(--gap) * 1px * 2), or store a length: --gap: 8px; margin: calc(var(--gap) * 2).
Write CSS for a .tag component whose background defaults to the page's --accent color, can be changed per tag with --tag-bg, and falls back to #ddd if neither is set.
Answer
.tag { background: var(--tag-bg, var(--accent, #ddd)); }
A --muted color is defined on :root as below. Inside .dark, --text is redefined, but --muted text keeps the light-theme color. Why, and how do you fix it?
:root {
--muted: color-mix(in srgb, var(--text) 60%, transparent);
}
Answer
--muted is computed on the root element, using the root's --text, and that computed value is what inherits. Redefining --text lower down doesn't recompute it. Declare --muted again inside .dark, or declare it on the elements that use it, so that it resolves with the local --text.
Previous: Math Functions: calc(), min(), max(), clamp(), round() and Trigonometry
Next: Registered Custom Properties With @property: Types, Inheritance and Animation

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.