Chapter 25 of 33

CSS Variables (Custom Properties)

Imagine your website's brand colour is #2563eb. It appears in buttons, links, borders, headings and focus rings: forty places across your CSS. Now the design team decides on a slightly different blue. You search and replace, miss two places, and accidentally change an unrelated colour that happened to have the same value.

Programming languages solved this problem long ago with variables. CSS has them too, officially called custom properties. They are much more powerful than a simple find-and-replace: they follow the cascade, they inherit, they can change inside media queries, and JavaScript can update them while the page is running. In this chapter we learn how to define and use them, how scope and inheritance work, fallbacks, the tricky "invalid at computed-value time" behaviour, theming (including dark mode), component variants, JavaScript access, and typed variables with @property.


What is a Custom Property?

A custom property is a property whose name starts with two dashes (--), defined by the author. Its value can be read anywhere it is in scope with the var() function.

:root {
  --primary: #2563eb;      /* define */
}

.button {
  background: var(--primary);   /* use */
}

a {
  color: var(--primary);
}

Change --primary in one place and every button and link updates. A few basic facts:

  • The name must start with --. That prefix ensures your names never clash with real CSS properties, present or future.

  • Names are case-sensitive: --primary and --Primary are two different variables. (Normal property names like COLOR are case-insensitive, but custom ones are not.)

  • A custom property is declared inside a rule, just like any other property. There is no "global variable" syntax outside rules.

  • "CSS variables" and "custom properties" mean the same thing. The specification is called CSS Custom Properties for Cascading Variables.

Why :root?

:root is a pseudo-class that matches the root element of the document, which in HTML is the <html> element. Because custom properties inherit, a value set on <html> is available to every element on the page. Writing :root instead of html is a convention; it also has the specificity of a class (0,1,0) instead of a type selector (0,0,1).

Browser support is complete: custom properties have worked in all major browsers since 2017 and are Baseline: widely available.


Scope and Inheritance

Custom properties are ordinary properties, so the usual rules from Specificity, Inheritance & the Cascade apply to them:

  • They inherit by default: a child sees its parent's value.

  • A value defined on an element overrides the inherited one for that element and its descendants. This gives you "local" variables.

  • If two rules set the same custom property on the same element, the normal cascade (specificity, then order) decides.

<p class="text">Normal text</p>
<div class="promo">
  <p class="text">Promo text</p>
</div>
:root {
  --accent: #0a7;      /* green, for the whole page */
}

.promo {
  --accent: purple;    /* redefined only inside .promo */
}

.text {
  color: var(--accent);
}

Output (rendered colours):

Normal text  → green   (inherits --accent from :root)
Promo text   → purple  (inherits --accent from .promo, the nearer ancestor)

One rule, .text { color: var(--accent); }, gives different results depending on where the element is. This is the key difference from preprocessor variables, which we compare at the end of the chapter.

How var() is resolved: the browser looks up the custom property's value on the element being styled, at the time it computes that element's styles. Whatever value that element has (its own or inherited) is substituted in.


Fallback Values

var() accepts a second argument, used when the variable is not defined:

.card {
  padding: var(--card-padding, 16px);
}

If --card-padding is not set on .card (or an ancestor), the padding is 16px.

Two details that surprise people:

/* 1. everything after the FIRST comma is the fallback, commas included */
.title {
  font-family: var(--heading-font, Georgia, serif);   /* fallback = "Georgia, serif" */
}

/* 2. fallbacks can be nested to try several variables in order */
.link {
  color: var(--link-color, var(--primary, blue));
}

In Chrome, with --heading-font undefined, the computed font-family is Georgia, serif, so the whole list worked as one fallback.

The fallback is also used when the variable is part of a cycle (for example --a: var(--b); --b: var(--a);). A cycle makes both variables invalid, so var(--a, green) gives green.


Building Values with calc()

A custom property's value is stored as a sequence of tokens (pieces of text), not as a number or colour. That has an important consequence:

:root {
  --gap: 10;
}

/* ❌ does NOT produce 10px; it produces the two tokens "10" and "px" */
.a { width: var(--gap)px; }

/* ✅ multiply by 1 unit */
.b { width: calc(var(--gap) * 1px); }   /* 10px */

In Chrome, .a got its default width (the declaration was invalid) and .b was exactly 10px wide. Storing unitless numbers and multiplying with calc() is a common technique, for example for spacing scales:

:root {
  --space: 0.5rem;
}

.stack-sm { gap: var(--space); }                 /* 0.5rem */
.stack-md { gap: calc(var(--space) * 2); }       /* 1rem   */
.stack-lg { gap: calc(var(--space) * 4); }       /* 2rem   */

Another consequence: an unregistered custom property doesn't calculate anything itself. If you set --total: calc(2 * 10px) and read it from JavaScript, you get the text calc(2 * 10px), not 20px. The calculation happens only where the variable is used in a real property (or if you register it with @property, shown later).


Where You Can and Can't Use var()

UsageWorks?
Any property value: color: var(--c)✅ Yes
Part of a value: border: 1px solid var(--c)✅ Yes
Inside functions: calc(), rgb(), clamp(), gradients✅ Yes
Inside another custom property: --btn-bg: var(--primary)✅ Yes
Property names: var(--prop): red❌ No
Selectors: .var(--name) { }❌ No
Media query conditions: @media (min-width: var(--bp))❌ No
Gluing units: var(--n)px❌ No (use calc())

Why not in media queries? Custom properties belong to elements (they are set on :root, .card and so on), but a media query is about the device and has no element to read a value from. We confirmed in Chrome that @media (min-width: var(--bp)) never matches. You can, however, do the opposite and change a variable inside a media query, which is very useful (see below).


Invalid at Computed-Value Time

This is the most important "gotcha" with variables, and a favourite interview question. Normally, if you write an invalid value, the browser throws that declaration away and an earlier one still applies:

p {
  color: red;
  color: 20px;     /* invalid → ignored at parse time → text stays red */
}

With var() it works differently:

body {
  color: navy;
}

p {
  --size: 20px;
  color: red;
  color: var(--size);   /* becomes "color: 20px" → invalid */
}

Result: the paragraph is navy, not red!

Why? When the browser parses color: var(--size), it can't know yet what --size will be (that depends on the element), so it accepts the declaration, and the later declaration beats color: red in the cascade. Only later, when computing styles for this specific element, does it substitute 20px and discover the value is invalid. By then red is long gone. The specification says the property then behaves as if it were unset:

  • for an inherited property like color: it inherits from the parent (navy);

  • for a non-inherited property like background: it takes its initial value (transparent).

Normal invalid value:   thrown away while parsing  → earlier declaration wins
Invalid after var():    accepted while parsing     → becomes "unset" at compute time

The same happens when you use an undefined variable without a fallback: background: yellow; background: var(--missing); gives a transparent background in Chrome, not yellow. Lesson: provide a fallback (var(--missing, yellow)) when a variable may not exist.


Pattern: Theming and Dark Mode

Variables make themes easy. Define semantic names (what the colour is for, not what it looks like), then switch their values:

:root {
  --bg: #ffffff;
  --text: #1f2937;
  --surface: #f3f4f6;
  --primary: #2563eb;
}

/* follow the operating system setting */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111827;
    --text: #e5e7eb;
    --surface: #1f2937;
    --primary: #60a5fa;
  }
}

/* the rest of the site never mentions actual colours */
body {
  background: var(--bg);
  color: var(--text);
}

.card {
  background: var(--surface);
}

.button {
  background: var(--primary);
}

Compare this with the dark mode example in Responsive Design & Media Queries: there, every rule had to be written twice. Here, the media query only changes four variables, and every component follows automatically.

Letting the user choose

Many sites also have a theme toggle button. Put the theme on an attribute of <html> and add a rule for it:

:root[data-theme="dark"] {
  --bg: #111827;
  --text: #e5e7eb;
  --surface: #1f2937;
  --primary: #60a5fa;
}
const button = document.querySelector("#theme-toggle");

button.addEventListener("click", () => {
  const root = document.documentElement;
  const isDark = root.dataset.theme === "dark";
  root.dataset.theme = isDark ? "light" : "dark";
});

Clicking the button sets data-theme="dark" on <html>; the attribute selector matches, the variables change, and the whole page repaints in dark colours. No class has to be added to individual elements.


Pattern: Component Variants

Inside a component, a "private" variable gives you clean variants:

.btn {
  --btn-bg: var(--primary);
  --btn-color: white;

  background: var(--btn-bg);
  color: var(--btn-color);
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
}

.btn--danger {
  --btn-bg: #dc2626;
}

.btn--ghost {
  --btn-bg: transparent;
  --btn-color: var(--primary);
}

Each variant only changes inputs; the actual background/color rules are written once. In Chrome, .btn was blue (rgb(37, 99, 235)) and .btn.btn--danger was red (rgb(220, 38, 38)). You can also override a variable for one special button with an inline style: <button class="btn" style="--btn-bg: green">.


Pattern: Responsive Variables

You can't put var() in a media query condition, but you can change variables inside one:

:root {
  --page-padding: 1rem;
  --heading-size: 1.75rem;
}

@media (width >= 900px) {
  :root {
    --page-padding: 3rem;
    --heading-size: 2.5rem;
  }
}

main { padding: var(--page-padding); }
h1   { font-size: var(--heading-size); }

All the responsive decisions live in one place, and the components just read the current values.


Reading and Writing Variables with JavaScript

:root {
  --primary: #2563eb;
}
const root = document.documentElement;

// read the computed value
console.log(getComputedStyle(root).getPropertyValue("--primary"));

// write a new value (as an inline style on <html>)
root.style.setProperty("--primary", "tomato");
console.log(getComputedStyle(root).getPropertyValue("--primary"));

// an undefined variable gives an empty string
console.log(getComputedStyle(root).getPropertyValue("--nope") === "");

Output:

#2563eb
tomato
true

As soon as setProperty() runs, every element using var(--primary) updates. Note that you must use setProperty() / getPropertyValue(): root.style.--primary is not valid JavaScript, and root.style.primary does nothing.

A neat use is passing values from JavaScript to CSS without touching individual properties, for example the mouse position for a spotlight effect:

document.addEventListener("mousemove", (event) => {
  document.body.style.setProperty("--mouse-x", event.clientX + "px");
  document.body.style.setProperty("--mouse-y", event.clientY + "px");
});
body {
  background: radial-gradient(
    circle at var(--mouse-x, 50%) var(--mouse-y, 50%),
    #fde68a,
    #ffffff 250px
  );
}

JavaScript only provides numbers; CSS decides what they look like.


Typed Variables with @property

Normal custom properties are just text, so the browser doesn't know whether --angle: 45deg is an angle. With @property you register a custom property with a type, an initial value and an inheritance rule:

@property --size {
  syntax: "<length>";
  inherits: false;
  initial-value: 10px;
}
DescriptorMeaning
syntaxThe type: "<length>", "<color>", "<number>", "<angle>", "<percentage>", ..., or "*" for anything
inheritstrue or false: does a child inherit the value? (required)
initial-valueValue when nothing is set (required unless syntax is "*")

What registration changes, all confirmed in Chrome:

  • Real computed values. With --size: calc(2 * 15px) on a registered <length>, JavaScript reads 30px, not the text calc(2 * 15px).

  • Controlled inheritance. With inherits: false, a child of that element doesn't see 30px; it gets the initial value, 10px.

  • Type checking. Setting a registered <angle> to 45 (no unit) is invalid, so the property falls back to its initial value instead of holding garbage.

  • Animation. Because the browser knows the type, it can smoothly interpolate between two values. An unregistered variable can only "jump". This allows effects like animating a gradient's angle or colour stops, which you will use in Transitions and Animations & Keyframes.

@property --angle {
  syntax: "<angle>";
  inherits: false;
  initial-value: 0deg;
}

.spinner-border {
  background: conic-gradient(from var(--angle), #2563eb, #93c5fd, #2563eb);
}

@property works in Chrome/Edge 85+, Safari 16.4+ and Firefox 128+, and is Baseline newly available since July 2024. In older browsers the property simply behaves like a normal, unregistered custom property, so the page still works, only without the smooth animation.


CSS Variables vs Preprocessor Variables

Before custom properties existed, developers used preprocessors such as Sass ($primary: #2563eb;). Both are still common, but they are fundamentally different:

Sass variables ($x)CSS custom properties (--x)
When resolvedAt build time, replaced by plain valuesAt run time, in the browser
Exists in the final CSS?NoYes
Follows cascade and inheritance (DOM-aware)No, only lexical scope in the Sass fileYes
Can change in media queries / per elementNo (value is fixed once compiled)Yes
JavaScript can read/change itNoYes
Usable in selectors, media queries, property namesYesNo
Needs a build stepYesNo

In modern projects, custom properties handle anything that changes at run time (themes, component variants, responsive values), and preprocessor variables are mainly used for things like breakpoints, which custom properties can't express in media queries.


Common Mistakes

  • Forgetting the dashes (primary: blue) or using one dash (-primary). It must be --primary.

  • Case mismatch: --Primary ≠ --primary.

  • Gluing units: var(--n)px is invalid; use calc(var(--n) * 1px).

  • Using var() in media query conditions or selectors. It never works there.

  • Expecting the earlier declaration to survive when var() produces an invalid value. The property becomes unset instead.

  • Defining variables on the wrong element. A variable set on .sidebar is invisible to elements outside the sidebar.

  • Naming by appearance (--blue). When the theme changes, --blue might hold dark grey. Prefer semantic names (--primary, --text, --surface).


Interview & Exam Questions

1. What is the difference between :root { --c: red; } and .box { --c: red; }?

Scope. On :root (the <html> element) the value is inherited by every element on the page. On .box it is available only to .box elements and their descendants. Inside a .box, its own value overrides whatever was inherited.

2. What colour is the text? body { color: green; } p { --x: 5px; color: blue; color: var(--x); }

Green. color: var(--x) wins the cascade over color: blue because it comes later and is accepted at parse time. At computed-value time it becomes color: 5px, which is invalid, so the property behaves as unset. color is inherited, so it takes the parent's green.

3. Why doesn't @media (min-width: var(--bp)) work?

Custom properties are set on elements and resolved per element through the cascade. A media query is evaluated for the whole document/device, with no element to read the variable from, so var() isn't allowed in media query conditions.

4. What does var(--font, Arial, sans-serif) fall back to?

Everything after the first comma: Arial, sans-serif.

5. How do you change a CSS variable from JavaScript?

With element.style.setProperty("--name", value), often on document.documentElement. Read it with getComputedStyle(element).getPropertyValue("--name"). All elements using that variable update automatically.

6. Why would you register a custom property with @property?

To give it a type, an initial value and controlled inheritance. The browser can then compute and validate it (e.g. calc() results become real lengths, invalid values fall back to the initial value), and, most visibly, transition and animate it smoothly, which unregistered variables can't do.

7. Give two differences between Sass variables and CSS custom properties.

Sass variables are replaced at build time and don't exist in the browser, while custom properties live in the browser at run time. Custom properties follow the cascade and inheritance and can be changed by media queries and JavaScript; Sass variables can't. On the other hand, Sass variables can be used in selectors and media queries, which custom properties can't.


Summary

  • Custom properties are declared with --name: value and used with var(--name); names are case-sensitive.

  • They cascade and inherit like normal properties: define globals on :root, override locally on any element.

  • var(--x, fallback) handles missing variables; everything after the first comma is the fallback.

  • Values are token lists: use calc(var(--n) * 1px), never var(--n)px.

  • var() works only in property values, not in selectors, property names or media query conditions.

  • An invalid substituted value makes the property unset (inherit or initial), not the earlier value.

  • Great for theming and dark mode, component variants and responsive values; JavaScript can read and set them.

  • @property registers typed variables that compute, validate and animate (Baseline since July 2024).

With variables in your toolkit, the next chapter, Transitions, will show how to animate smoothly between values, including registered custom properties.