Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Variables

CSSLesson 2425 min

What you'll walk away with

  • Declare custom properties and read them with var(), including a fallback value
  • Use inheritance to override a custom property for one component or one theme
  • Understand that values are token text, not types, and use calc() instead of var(--n)px
  • Separate raw palette tokens from semantic tokens to build light and dark themes

Explain it simply

Explain it simply

Suppose your brand color #1d4ed8 is typed fifty times across ten files. The day it changes, you hunt down every copy, and the one you miss leaves a button in the old color. A custom property stores that value once under a name such as --color-primary, and everywhere else simply asks for var(--color-primary).

Unlike Sass variables, these values stay alive in the browser. You can switch to dark mode while the page runs, override a color inside one card only, or change a value from JavaScript.

Problem → Why → Solution

The problem: padding that silently disappears

For a spacing scale you declare --spacing: 16 without a unit, then write padding: var(--spacing)px on a card. The padding comes out as 0, not 16px, and the console shows no error. DevTools even lists --spacing as "16", which makes the bug more confusing.

:root {
  --spacing: 16;
}

.card {
  padding: var(--spacing)px;   /* computed padding: 0px */
}

Why isn't it 16px?

var() substitutes token text, not a typed value. The number token 16 followed by a separate px token never becomes the dimension 16px. Because declarations containing var() cannot be checked at parse time, the result is invalid only at computed-value time, and the property then behaves as unset, giving padding its initial value of 0. Use calc(var(--spacing) * 1px), or store the unit: --spacing: 16px.

Core concept: runtime values that cascade

A custom property is a property whose name starts with --, written inside a rule just like color or padding. That means the cascade applies: specificity and source order decide which value wins, and the value inherits from parent to child like any inherited property. Declare it on :root (the html element) and the whole page sees it; redeclare it on .card and only that card and its descendants see the new value. Names are case-sensitive, so --Brand and --brand are two different properties.

var(--name, fallback) reads the value. The fallback is used only when --name is not defined at all (or is the initial value), not when it is defined but unusable. Fallbacks can nest another var(): var(--button-bg, var(--color-primary)) reads as "use the component's own value if set, otherwise the theme's".

The browser substitutes var() at computed-value time. If the substituted value is invalid for that property, the declaration is "invalid at computed-value time" and the property becomes unset: an inherited property takes the parent's value, any other property its initial value. Crucially, an earlier declaration in the same rule, such as color: red;, is not used as a backup, because the cascade already discarded it.

When a custom property's value contains var(), it is resolved on the element where it is declared, and the resolved value is what children inherit. If :root says --bg: var(--gray) and .card redeclares --gray, var(--bg) inside the card still gives the old color, because --bg was already resolved on :root. To change it inside a component, redeclare the property you actually use, --bg. A cycle such as --a: var(--b); --b: var(--a); makes both invalid, so var() falls back.

JavaScript can read and write them too: getComputedStyle(el).getPropertyValue("--spacing") returns a string such as "16", and el.style.setProperty("--spacing", "24px") updates everything below that element at once.

Mental model: how var() resolves
  1. Cascade picks the value of --name
  2. Inheritance carries it down to children
  3. var() is replaced by the token text
  4. Invalid result: the property is unset

A custom property is find-and-replace text; the type is only checked where var() is used.

General pattern

css
:root {
  --token-name: value;                  /* global default */
}

.scope {
  --token-name: other-value;            /* override for this subtree */
}

.element {
  property: var(--token-name, fallback);
  size: calc(var(--unitless-number) * 1px);
}

Keep global defaults on :root; redeclaring the property on any selector overrides it for that subtree only. To turn a unitless number into a length, multiply it by a unit inside calc().

Example: a button and a card sharing tokens

Here three tokens are declared once on :root and reused by both .button and .card. In the DevTools Styles panel, change --card-radius on :root to 4px and watch the button and the card update together.

:root {
  --primary-color: #77f5ff;
  --text-color: #eaf2ff;
  --card-radius: 16px;
}

.button {
  background: var(--primary-color);
  color: #041013;
  border-radius: var(--card-radius);
}

.card {
  color: var(--text-color);
  border-radius: var(--card-radius);
}

Code breakdown

  1. :root:root {

    :root is the html element. Custom properties declared here inherit, so every element on the page can read them.

  2. --primary-color--primary-color: #77f5ff;

    Stores the hex color text under a name that starts with --. At this point the browser does not check that it is a color.

  3. var(--primary-color)background: var(--primary-color);

    At computed-value time #77f5ff is substituted and only then checked against background. Note that the button's color: #041013 is hard-coded rather than a token, so a theme change would miss it; it deserves a semantic token too.

  4. shared radiusborder-radius: var(--card-radius);

    Both .button and .card contain this line, so they share one corner radius, and the 16px value is edited in exactly one place.

You should see
The button gets a #77f5ff cyan background, #041013 text and a 16px radius; the card gets #eaf2ff text and the same 16px radius. Changing --card-radius on :root updates both at once.

Palette tokens vs semantic tokens: building themes

Split tokens into two layers when building themes. Palette tokens (--blue-600, --gray-900) say what a color is and never change. Semantic tokens (--color-bg, --color-text, --color-primary) say what a color is for, and each theme points them at different palette tokens. Components only use semantic tokens, so a dark theme is nothing more than re-pointing them.

:root {
  --gray-50: #f9fafb;
  --gray-900: #111827;
  --color-bg: var(--gray-50);
  --color-text: var(--gray-900);
}

@media (prefers-color-scheme: dark) {
  :root {
    --color-bg: var(--gray-900);
    --color-text: var(--gray-50);
  }
}

body { background: var(--color-bg); color: var(--color-text); }

Typed custom properties

The @property rule registers a custom property with a syntax such as <color> or <length> and an initial value. A registered property rejects invalid values and can even be animated. Current major browsers support it, but check it against your own target browsers.

In real projects

Where this shows up in real projects

Design systems publish color, spacing, radius, shadow and font-size tokens, often generated straight from the design tool into a file of CSS custom properties. A dark mode toggle just flips one attribute, <html data-theme="dark">, and the semantic tokens are redefined under a [data-theme="dark"] selector. JavaScript changes the attribute; the cascade does the rest.

Component libraries expose component-level hooks such as --button-bg, so users create a new variant by redeclaring one custom property on a class. Passing data from markup to CSS is common too: style="--progress: 70%" on an element, then width: var(--progress) in the stylesheet, draws a progress bar without any per-value CSS. The server only writes the value into the HTML; the stylesheet never needs to be regenerated.

Common mistakes

Common mistakes

1. Expecting the fallback to rescue a bad value

With --gap: red; and margin-left: var(--gap, 8px);, you get 0, not 8px. Because --gap exists, the fallback is never consulted; red is substituted, is invalid for margin, and the property becomes unset. Fallbacks only cover missing variables.

2. Wiring components to palette names

A card with background: var(--white) forces you to make --white black in dark mode, and the name stops matching the value. Components should use semantic names such as --color-surface and leave palette tokens to the theme file.

3. Declaring a token in the wrong scope

Declare --accent on .sidebar and use var(--accent) in .header, and the header gets nothing because it is not inside the sidebar; for color, it quietly falls back to the inherited color. Tokens the whole page needs belong on :root.

Best practices

Best practices

  • Store length tokens with their unit (--space: 8px) and keep unitless numbers for calc().
  • Let components use semantic tokens and hooks like --button-bg, and keep palette tokens in the theme file.
  • Give var() a fallback wherever a token might be missing, such as in shared or third-party components.
  • When a value does not show, check the Computed tab: an invalid-at-computed-value-time declaration shows the initial or inherited value.

Mini challenge

Mini challenge: a themeable button

Build a token set that separates palette and semantic tokens, then drive a button component, a danger variant and a dark panel purely through custom properties.

  • On :root, declare palette tokens (--blue-600, --red-600, --gray-50, --gray-900), semantic tokens (--color-bg, --color-text, --color-primary) and --space: 8px
  • Inside [data-theme="dark"], re-point only the two semantic color tokens
  • .button takes its background from var(--button-bg, var(--color-primary)) and derives its padding from --space
  • .button.danger changes nothing but --button-bg
tokens.html
<style>
  /* TODO: :root - palette tokens, semantic tokens pointing at them, --space */

  /* TODO: [data-theme="dark"] - re-point --color-bg and --color-text */

  /* TODO: .panel - background, text color, padding of two spaces */

  /* TODO: .button - background from --button-bg or the primary color,
     white text, padding of one space by two spaces, no border, 6px radius */

  /* TODO: .button.danger - override only --button-bg */
</style>
<div class="panel">
  <button class="button">Save</button>
  <button class="button danger">Delete</button>
</div>
<div class="panel" data-theme="dark">
  <button class="button">Save</button>
</div>

Expected: The first panel has an off-white (#f9fafb) background and 16px padding; Save is blue (#1d4ed8) and Delete red (#dc2626), both with 8px 16px padding. The second panel is dark (#111827) with off-white text, and its Save button stays blue.

Show hint

Point semantic tokens at palette tokens with var(): --color-bg: var(--gray-50). For padding, var(--space) calc(var(--space) * 2) works. In .danger do not rewrite background; just declare --button-bg.

Show solution
tokens.html
<style>
  :root {
    --blue-600: #1d4ed8;
    --red-600: #dc2626;
    --gray-50: #f9fafb;
    --gray-900: #111827;
    --color-bg: var(--gray-50);
    --color-text: var(--gray-900);
    --color-primary: var(--blue-600);
    --space: 8px;
  }
  [data-theme="dark"] {
    --color-bg: var(--gray-900);
    --color-text: var(--gray-50);
  }
  .panel {
    background: var(--color-bg);
    color: var(--color-text);
    padding: calc(var(--space) * 2);
  }
  .button {
    background: var(--button-bg, var(--color-primary));
    color: white;
    padding: var(--space) calc(var(--space) * 2);
    border: 0;
    border-radius: 6px;
  }
  .button.danger { --button-bg: var(--red-600); }
</style>
<div class="panel">
  <button class="button">Save</button>
  <button class="button danger">Delete</button>
</div>
<div class="panel" data-theme="dark">
  <button class="button">Save</button>
</div>

Quick quiz 1 / 3

Given :root { --size: 20; } and .box { width: var(--size)px; }, what is the width of .box?

Quick quiz 2 / 3

With :root { --brand: blue; } and .card { --brand: orange; }, what color does color: var(--brand) give an <a> inside .card?

Quick quiz 3 / 3

With --gap: red; defined, what does .item { margin-left: var(--gap, 8px); } produce?

What to remember

  • Custom properties (--name) are runtime values that cascade and inherit; redeclaring one on a selector overrides it for that subtree.
  • The fallback in var(--name, fallback) only covers a missing variable, not an invalid value.
  • Values are token text: use calc(var(--n) * 1px), not var(--n)px; an invalid result silently makes the property unset.
  • With palette and semantic tokens separated, a theme is just a re-pointing of the semantic tokens.

CSS reference — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.