Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 139 ยท Values and Units

Custom Properties (CSS Variables)

Learn CSS custom properties from --name and var() fallbacks to scope, inheritance, theming, changing values with JavaScript and typed @property rules.

As a stylesheet grows, the same values appear again and again: the brand color in forty places, the same border radius on every card, the same spacing step everywhere. Change the brand color and you have forty edits to make. Custom properties, often called CSS variables, let you name a value once and use it everywhere.

They do far more than save typing. Unlike variables in preprocessors such as Sass, custom properties are live: they follow the cascade, they inherit, they can change in a media query or on hover, and JavaScript can read and set them while the page runs. That makes them the foundation of modern theming and component design.

Defining and using a custom property

A custom property is any property whose name starts with two dashes. You read it with the var() function:

CSS
:root {
  --brand: #4f46e5;
  --radius: 10px;
  --space: 1rem;
}

.button {
  background: var(--brand);
  border-radius: var(--radius);
  padding: calc(var(--space) / 2) var(--space);
}

A few details:

  • Names are case-sensitive. --brand and --Brand are two different properties.
  • :root is the <html> element, the usual home for global values, since everything inherits from it.
  • The value can be almost anything: a color, a length, a list of shadows, even half a value like 0 4px. The browser doesn't check it until the variable is used.
One change, many updates

Fallbacks

var() accepts a second argument, a fallback used when the property isn't defined:

CSS
.alert {
  color: var(--alert-color, #b91c1c);          /* red unless --alert-color is set */
  padding: var(--alert-padding, 8px 12px);     /* everything after the first comma is the fallback */
  font-family: var(--alert-font, var(--body-font, system-ui));  /* fallbacks can nest */
}

Fallbacks are perfect for components: they work out of the box, and anyone can customize them by setting the variable, without touching the component's CSS.

The fallback is used when the property is missing, not when its value is wrong for the context. If --size: red and you write width: var(--size, 100px), the fallback isn't used: width: red is invalid, and the property becomes unset (its inherited or initial value). This is called invalid at computed-value time, and it's why a typo in a variable can make a style silently disappear instead of falling back to an earlier rule.

Scope and inheritance

Custom properties are ordinary properties, so they follow the normal rules of the cascade and of inheritance. They inherit by default: set one on an element and all its descendants can read it. Set it again lower in the tree and that subtree sees the new value.

That gives you scoped variables for free:

Variables are inherited and can be overridden

Notice the pattern: the .badge rule never changes. Variants and regions only set --accent. That keeps components small and makes every variant one line long.

Building with custom properties

Design tokens

Most projects define a set of tokens on :root: colors, spacing steps, radii, font stacks, shadows. Components use only tokens, so the whole design can be adjusted from one place.

CSS
:root {
  --color-text: #1e293b;
  --color-surface: #ffffff;
  --color-accent: oklch(0.55 0.2 265);
  --space-1: 0.25rem;
  --space-2: 0.5rem;
  --space-3: 1rem;
  --radius-m: 8px;
  --shadow-1: 0 1px 2px rgb(0 0 0 / 0.08), 0 2px 8px rgb(0 0 0 / 0.06);
}

Units and math

A variable can hold a plain number, and calc() can turn it into any unit. This is the correct way; gluing a unit onto var() doesn't work:

CSS
.grid { --cols: 3; }

.grid {
  grid-template-columns: repeat(var(--cols), 1fr);
  gap: calc(var(--cols) * 4px);        /* correct: 12px */
  /* margin: var(--cols)px;            wrong: becomes "3 px", which is invalid */
}

Changing values in media queries and states

Because they're live, variables can change under any condition, and every rule that uses them updates:

CSS
:root { --gutter: 1rem; }

@media (width >= 50rem) {
  :root { --gutter: 2rem; }
}

.link { --underline: 1px; text-decoration-thickness: var(--underline); }
.link:hover { --underline: 3px; }

Theming and JavaScript

Themes are where custom properties shine. Define each theme as a set of variable values, and switch between them by changing a class or attribute. JavaScript can also set a single variable directly with style.setProperty() and read the current value with getComputedStyle():

JavaScript
const root = document.documentElement;
root.style.setProperty("--brand", "#e11d48");            // set
getComputedStyle(root).getPropertyValue("--brand");      // read: "#e11d48"
root.style.removeProperty("--brand");                    // go back to the stylesheet value

The demo below combines both: buttons switch whole themes with a data-theme attribute, and the controls change individual variables live.

Theme switcher with custom properties and JavaScript

Pick an accent color, then switch themes: your inline --accent keeps winning because inline styles beat the theme selectors. Press "Reset overrides" and the theme's own accent returns.

In a real site you'd also save the visitor's choice (for example in localStorage, which these sandboxed previews can't use) and respect their system preference. The Dark Mode lesson builds that out fully.

Typed custom properties with @property

Normally the browser treats a custom property's value as an untyped chunk of text. That has a side effect: it can't animate it. If you transition --angle from 0deg to 180deg, the browser doesn't know those are angles, so it just flips from one to the other.

The @property rule registers a custom property with a type, an initial value and an inheritance setting:

CSS
@property --angle {
  syntax: "<angle>";
  inherits: false;
  initial-value: 0deg;
}
  • syntax is the type: "<length>", "<color>", "<number>", "<percentage>", "<angle>", "<length-percentage>" and others, or "*" for anything.
  • inherits says whether descendants inherit it. Setting false is a small performance win for values only one element needs.
  • initial-value is used when nothing sets the property, and it is required unless the syntax is "*".

Once the browser knows the type, it can interpolate the value, which unlocks effects such as animated gradients:

Animating a gradient with @property

The element itself doesn't rotate; only the gradient's starting angle animates. Without the @property rule, the animation would do nothing visible.

Registration also adds type checking: if a registered <color> property gets the value 10px, the declaration is invalid and the property keeps its initial value, so you get a predictable result instead of a broken one. JavaScript can register properties too, with CSS.registerProperty({ name: "--angle", syntax: "<angle>", inherits: false, initialValue: "0deg" }).

Support: custom properties and var() work in every browser you need to care about. @property arrived in Chrome and Edge in 2020 and in Safari in 2023, but Firefox only added it in mid-2024 (version 128). Treat it as a progressive enhancement: make sure the design still works if the animation doesn't run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does color: var(--text, #333) do when --text is not defined anywhere?

    The fallback is used when the custom property has no value.
  2. 2. A parent sets --gap: 2rem and a child sets --gap: 1rem. What does a grandchild that uses var(--gap) get?

    Custom properties inherit, and the nearest ancestor that sets one wins, just like color or font.
  3. 3. With --n: 4, which declaration gives a 16px margin?

    Multiply the number by a length inside calc(). Appending a unit to var() creates two separate tokens, which is invalid.
  4. 4. How do you change a custom property from JavaScript?

    style.setProperty() sets any property by name, including custom ones. Read it back with getComputedStyle(el).getPropertyValue('--brand').
  5. 5. What does registering a custom property with @property make possible?

    An untyped custom property can't be interpolated. With a syntax like <angle>, the browser can animate it smoothly.

Summary

  • Define custom properties with --name: value and read them with var(--name, fallback); names are case-sensitive.
  • They follow the cascade and inherit, so you can override them per region, per variant or per state.
  • If a variable's value is wrong where it's used, the property becomes unset; the fallback only covers missing variables.
  • Store numbers and convert them with calc(var(--n) * 1px); don't append units to var().
  • Themes are just different sets of variable values; JavaScript uses style.setProperty() and getComputedStyle().
  • @property gives a variable a type and initial value, which enables animation; it's been in all major browsers only since 2024.

Next: Advanced Math Functions: round(), mod() and Trigonometry.