Custom Properties (CSS Variables): The Token System Every Project Needs
Use CSS custom properties as design tokens: primitive, semantic and component tiers, dark mode, @property, fallbacks, and the traps that break them.

A rebrand lands. The new accent color has to go live by Friday. A search for the old hex code finds 214 matches, plus three slightly different blues someone eyedropped from a screenshot, plus an rgba() version used for hover states. The color change is easy. Knowing which blue meant “brand”, which meant “link” and which meant “info banner” is the actual work, and nobody wrote that down.
CSS custom properties, often called CSS variables, are properties whose names start with two dashes, such as --color-accent. You read them with the var() function. Unlike preprocessor variables, they exist at runtime: they cascade, inherit down the DOM tree, change inside media and container queries, and can be read and set from JavaScript. Design tokens are the named decisions of a design system (colors, spacing, type sizes, radii) stored in one place so every component uses the same values.
My position: the hard part of tokens is naming intent, not storing values. Every project needs a semantic tier between raw values and components, even a small one. Without it, custom properties just move the 214 hex codes into 214 var(--blue-600) calls.
How custom properties actually work
You declare a custom property like any other property, and it follows the same cascade rules described in the cascade and inheritance guide.
:root {
--radius: 8px;
--space: 1rem;
}
.card {
border-radius: var(--radius);
padding: var(--space);
}
.card--compact {
--space: 0.5rem; /* only this card and its descendants see 0.5rem */
}
Four properties of the mechanism matter in practice:
- They inherit. Every custom property inherits by default, so a value set on
:rootis visible everywhere and a value set on a component is visible inside it. - The DOM scopes them, not the file. Redefining
--spaceon.card--compactchanges it for that subtree only. - They resolve at computed-value time.
var()is substituted per element, after the cascade, which is why the same rule can produce different results on different elements. - Names are case-sensitive.
--Accentand--accentare two different properties.
Custom properties vs Sass variables
| Question | Sass variable ($accent) |
Custom property (--accent) |
|---|---|---|
| When is it resolved? | At build time, once | In the browser, per element |
| Can it change in a media query? | No, the output is static | Yes |
| Does it inherit through the DOM? | No | Yes |
| Can JavaScript read or change it? | No | Yes |
| Can it be used in a media query condition? | Yes | No |
| Can it be animated? | Not applicable | Yes, once registered with @property |
Preprocessor variables still have one job custom properties cannot do: values inside @media conditions. @media (width > var(--bp)) does not work, because media queries are evaluated before any element exists to hold the property. For breakpoints, use container queries, or keep a build-time constant.
The three-tier token system
A token system that survives a rebrand has three tiers. Each tier may only reference the tier directly below it.
- Primitive tokens are raw values with descriptive names:
--blue-600,--gray-100,--size-4. They say what a value is, not where you use it. - Semantic tokens name intent:
--color-text,--color-surface,--color-accent,--color-danger,--space-gap. Components use these. - Component tokens are optional hooks for one component:
--button-bg,--card-padding. They default to semantic tokens and exist so callers can customize without overriding selectors.
/* 1. Primitives: the palette. Nothing outside this block uses them directly. */
:root {
--blue-500: oklch(62% 0.19 255);
--blue-600: oklch(55% 0.19 255);
--gray-50: oklch(98% 0.005 255);
--gray-900: oklch(22% 0.02 255);
--red-600: oklch(55% 0.21 27);
}
/* 2. Semantic tokens: what each value means. Themes remap this tier only. */
:root {
--color-text: var(--gray-900);
--color-surface: var(--gray-50);
--color-accent: var(--blue-600);
--color-danger: var(--red-600);
--radius-control: 6px;
}
/* 3. Component tokens: hooks with defaults. */
.button {
--button-bg: var(--color-accent);
--button-fg: white;
background: var(--button-bg);
color: var(--button-fg);
border-radius: var(--radius-control);
}
.button--danger {
--button-bg: var(--color-danger);
}
Now the rebrand is one line: point --color-accent at a new primitive. Every component that meant “brand accent” changes, and the info banner that happened to share the same blue does not, because it references --color-info. The semantic tier is where that knowledge lives. The palette values use oklch(), which makes generating consistent scales much easier; the oklch() guide shows how.
Spacing and type scales
Spacing and font sizes work best as small, fixed scales. A fluid type scale with clamp() lets sizes grow with the viewport without a breakpoint per size:
:root {
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 1rem;
--space-4: 1.5rem;
--space-5: 2.5rem;
--text-sm: clamp(0.875rem, 0.84rem + 0.15vw, 0.95rem);
--text-base: clamp(1rem, 0.95rem + 0.25vw, 1.125rem);
--text-xl: clamp(1.4rem, 1.2rem + 1vw, 2rem);
}
Keep the rem part in every clamp(). A size built only from vw ignores the reader’s browser font-size setting, which fails WCAG’s resize-text requirement for people who need larger text.
Theming and dark mode
With a semantic tier, a theme is just a different mapping. The cleanest approach for light and dark uses the light-dark() function, supported in every major browser since 2024. It returns its first argument in a light color scheme and its second in a dark one, based on the color-scheme property.
:root {
color-scheme: light dark; /* follow the operating system by default */
--color-text: light-dark(var(--gray-900), var(--gray-50));
--color-surface: light-dark(var(--gray-50), var(--gray-900));
--color-accent: light-dark(var(--blue-600), var(--blue-500));
}
/* A manual toggle just forces the scheme */
:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }
Setting color-scheme also switches native form controls, scrollbars and the default canvas color, so you get a correct dark mode for elements you never styled. If you need more than two themes, such as a high-contrast or a seasonal theme, remap the semantic tokens under a [data-theme] selector instead.
Component APIs with custom properties
Custom properties work well as a public styling API for components. A caller sets a property instead of writing a higher-specificity override:
/* Caller code: no selector fight, no !important */
.pricing .button { --button-bg: var(--color-success); }
One refinement keeps the API tidy. Use a “private” property for the value the component actually reads, and let the public one feed it with a fallback:
.badge {
--_bg: var(--badge-bg, var(--color-accent));
--_fg: var(--badge-fg, white);
background: var(--_bg);
color: var(--_fg);
}
The underscore is just a naming convention, but it tells other developers which properties you should set from outside. It also stops a --badge-bg set on some ancestor for a different badge from being overwritten by the component itself.
Fallbacks and the invalid-at-computed-value-time trap
The second argument to var() is a fallback: var(--gap, 1rem). The browser uses it only when the custom property is not defined at all, or is set to the special initial value. The browser ignores it when the property is defined but its value makes no sense for the property using it.
:root { --size: red; }
.box {
width: 200px;
width: var(--size, 300px); /* what width does .box get? */
}
Many people expect 200px, from the previous declaration, or 300px, from the fallback. The answer is auto. The browser cannot know whether var() will produce a valid value until computed-value time, so it accepts the declaration at parse time and discards the earlier one. At computed-value time, red is not a valid width, so the declaration becomes “invalid at computed-value time” and width falls back to unset: its inherited value for inherited properties, its initial value otherwise. The spec calls this the guaranteed-invalid behavior, and it is the reason the old “declare a fallback line first” trick does not work with var().
The defense is @property, which gives a property a type.
Registered properties with @property
The @property rule registers a custom property with a syntax, an inheritance flag and an initial value. It has been available in all major browsers since mid-2024.
@property --card-padding {
syntax: "<length>";
inherits: false;
initial-value: 16px;
}
Registration changes three things:
- Type checking. The browser rejects a value that does not match the syntax, and the property uses its
initial-valueinstead of producing an invalid result downstream. - Controlled inheritance. With
inherits: false, a value set on a card does not leak into a nested card. That one flag solves most “my nested component picked up the parent’s token” bugs. - Animation. Unregistered custom properties are just token streams, so the browser cannot interpolate them and they flip at the midpoint. A registered
<angle>,<color>or<length>animates smoothly, which enables effects such as animated gradients.
@property --angle {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}
.spinner-border {
background: conic-gradient(from var(--angle), var(--color-accent), transparent 70%);
animation: spin 1.2s linear infinite;
}
@keyframes spin {
to { --angle: 360deg; }
}
@media (prefers-reduced-motion: reduce) {
.spinner-border { animation-duration: 6s; }
}
The initial-value must be computationally independent, so 16px is allowed but 1em is not, because em depends on the element’s font size. Use the JavaScript equivalent, CSS.registerProperty(), only when you need to register properties dynamically.
Reading and writing tokens from JavaScript
// Read the resolved value on a specific element
const accent = getComputedStyle(document.documentElement)
.getPropertyValue("--color-accent").trim();
// Write a value on the smallest element that needs it
card.style.setProperty("--tilt", `${angle}deg`);
Set frequently changing values, such as pointer position or scroll progress, on the smallest element that needs them. Changing a custom property on :root forces the browser to recalculate style for every element that might inherit it, which on a large page can cost several milliseconds per change.
Naming conventions that scale
| Tier | Pattern | Examples |
|---|---|---|
| Primitive | --{hue}-{step}, --size-{n} |
--blue-600, --size-4 |
| Semantic | --{category}-{role}[-{state}] |
--color-text-muted, --color-accent-hover, --space-gap |
| Component, public | --{component}-{property} |
--button-bg, --card-padding |
| Component, private | --_{property} |
--_bg, --_gap |
Frequently Asked Questions
What is the difference between CSS custom properties and CSS variables?
They are the same feature. The specification calls them custom properties, and the var() function reads them, which is why most developers call them CSS variables.
Should I still use Sass variables?
Only for values you must know at build time, such as breakpoints inside @media conditions. For colors, spacing, typography and anything that themes or changes at runtime, custom properties are more capable because they cascade and can change per element.
Why is my var() fallback not used?
The fallback applies only when the custom property is undefined. If the property is defined with a value that is invalid for the property using it, the declaration becomes invalid at computed-value time and the property resets to its inherited or initial value. Register the property with @property to get type checking.
What are design tokens in CSS?
Design tokens are named design decisions such as colors, spacing steps, font sizes and radii. In CSS you usually store them as custom properties and organize them into primitive values, semantic names that describe intent, and optional component-level hooks.
Name the intent, not the value
Storing values in custom properties takes an afternoon. Deciding what each value means is the work that pays off at the next rebrand, the next theme and the next new developer. Build the semantic tier first, keep components on it, and the palette becomes a detail you can swap. The tokens built here feed directly into cascade layers and the vanilla CSS vs Tailwind decision, since Tailwind v4 is itself built on custom properties.
Rule of thumb: if a token’s name would be wrong after a rebrand, it belongs in the primitive tier.
Originally posted on 8 May 2025 and post last modified on 8 May 2025