Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

CSS Variables and Custom Properties: How to Build Scalable Themes

CSS custom properties let components change appearance without duplicating rules, but they are not Sass or JavaScript variables. Their declaration scope and computation timing determine the result. These examples build a theme system, diagnose inheritance errors and control values at runtime.

Published Written by Reading time 8 min read
On this page Contents: quick navigation between sections

How should design tokens be organized?

<article class="card">
  <h2>Standard plan</h2>
  <button class="button" type="button">Select</button>
</article>

<article class="card card--featured">
  <h2>Premium plan</h2>
  <button class="button" type="button">Select</button>
</article>
:root {
  --palette-blue: #1747a6;
  --palette-purple: #6435a5;
  --color-action: var(--palette-blue);
  --space-4: 1rem;
}

.card {
  --card-action: var(--color-action);

  padding: var(--space-4);
}

.card--featured {
  --card-action: var(--palette-purple);
}

.button {
  padding: 0.5rem var(--space-4);
  border: 0;
  border-radius: 0.5rem;
  background-color: var(--card-action, var(--color-action));
  color: #fff;
  font: inherit;
}

Separate primitive values (palette and spacing), semantic tokens describing a purpose, and local component tokens. A brand change then does not require editing every button selector. [1][2]

Both buttons share one rule, but the featured card overrides the local token. The first is blue and the second purple. Do not declare the default --card-action on the button itself if it should inherit the card's value.

How can system and explicit themes coexist?

<main class="surface">
  <h1>Account</h1>
  <label for="name">Display name</label>
  <input id="name" name="name" autocomplete="nickname" />
  <section class="surface" data-theme="dark">
    <h2>Dark preview</h2>
    <p>Local theme, independent of the page.</p>
  </section>
</main>
:root,
[data-theme="light"] {
  color-scheme: light;
  --color-surface: #fff;
  --color-text: #172033;
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) {
    color-scheme: dark;
    --color-surface: #172033;
    --color-text: #f3f5f9;
  }
}

[data-theme="dark"] {
  color-scheme: dark;
  --color-surface: #172033;
  --color-text: #f3f5f9;
}

.surface {
  padding: 1rem;
  background-color: var(--color-surface);
  color: var(--color-text);
}

Start with light defaults and apply prefers-color-scheme only when the document has no explicit data-theme. Redefine semantic values for each theme. color-scheme tells the browser how native controls should render; it does not automatically recolor custom styles. [4][5]

Setting data-theme="light" on html overrides a dark system preference, while the dark preview keeps its own theme. If persisting a choice, set the attribute on the server or before first paint to reduce a wrong-theme flash. Check text, focus and control contrast in both themes.

Why does an alias not change when its source is overridden?

<div class="preview">
  <p class="original">Inherited alias</p>
  <p class="corrected">Locally resolved alias</p>
</div>
:root {
  --brand: #1747a6;
  --accent: var(--brand);
}

.preview {
  --brand: #6435a5;
}

.original,
.corrected {
  color: var(--accent);
}

.corrected {
  --accent: var(--brand);
}

An unregistered custom property is computed on the element where it is declared before its computed value is inherited. The root --accent therefore resolves to blue before .preview changes --brand. [1]

The first paragraph stays blue; the second is purple because it declares the alias again in the local scope. Define dependent aliases at the theme boundary where their source tokens change.

Why does var() ignore the fallback?

<div class="samples">
  <p class="missing">Missing token</p>
  <p class="invalid">Invalid color</p>
  <p class="cyclic">Cyclic tokens</p>
</div>
.samples {
  color: #172033;
}

.missing {
  color: var(--undefined-color, #1747a6);
}

.invalid {
  --accent: 12px;

  color: #1747a6;
  color: var(--accent, #6435a5);
}

.cyclic {
  --first: var(--second);
  --second: var(--first);

  color: var(--first, #6435a5);
}

A fallback is used when the reference cannot supply a value, for example a missing property or a cycle. It does not validate the receiving property's type. The token 12px is acceptable for an unregistered custom property but not for color. [1][3][10]

The second paragraph inherits #172033, not the previous blue declaration or the purple fallback: the cascade already selected the var() declaration. The first is blue and the third purple because the cycle invalidates both tokens. Register properties when a specific type is required.

When should a property be registered with @property?

<div class="notice">
  <p class="notice__message">Independent default</p>
  <p class="notice__message notice__message--invalid">Invalid value</p>
</div>
@property --notice-color {
  syntax: "<color>";
  inherits: false;
  initial-value: #1747a6;
}

.notice {
  --notice-color: #6435a5;

  color: #1747a6;
}

.notice__message {
  color: var(--notice-color, #1747a6);
}

.notice__message--invalid {
  --notice-color: 12px;
}

Registration defines syntax, inheritance and an initial value. For syntax other than *, the initial value must be computationally independent; 16px works for a length but 1em depends on the font. [6][7]

Both messages are blue: inherits: false prevents default inheritance and 12px fails the <color> syntax. Browsers without @property ignore the registration, so provide a separate safe base style when typed behavior is essential.

Without @property support, the first message can inherit the purple token and the second inherits the parent text color. Setting the parent color to blue provides a readable color even with the invalid token, but does not guarantee identical appearance for both messages. [6][7][10]

How can a variable animate a gradient?

<button class="action" type="button">Continue</button>
@property --action-angle {
  syntax: "<angle>";
  inherits: false;
  initial-value: 0deg;
}

.action {
  --action-angle: 0deg;

  padding: 0.75rem 1rem;
  border: 0;
  border-radius: 0.5rem;
  background: linear-gradient(var(--action-angle), #1747a6, #6435a5);
  color: #fff;
  font: inherit;
  transition: --action-angle 250ms ease;
}

.action:hover,
.action:focus-visible {
  --action-angle: 180deg;
}

@media (prefers-reduced-motion: reduce) {
  .action {
    transition: none;
  }
}

Unregistered tokens do not define interpolation for angles or numbers. Registering an <angle> enables interpolation of the angle used in a gradient; animating background-image itself does not guarantee this transition. [6][7]

The button changes gradient direction on hover or visible focus. prefers-reduced-motion disables the transition while preserving the visual state. Do not assume GPU-only execution: gradients may require repainting.

How can JavaScript update variables without rebuilding the DOM?

<label for="spacing">Card spacing</label>
<input id="spacing" type="range" min="0" max="32" value="16" />
<div class="layout" id="layout">
  <article>First card</article>
  <article>Second card</article>
</div>
.layout {
  --layout-gap: 16px;

  display: grid;
  gap: var(--layout-gap);
}

.layout article {
  padding: 1rem;
  border: 1px solid currentColor;
}
export function mountSpacingControl() {
  const spacing = document.getElementById("spacing");
  const layout = document.getElementById("layout");

  if (!(spacing instanceof HTMLInputElement) || !(layout instanceof HTMLElement)) {
    throw new Error("Missing spacing controls");
  }

  const propertyName = "--layout-gap";
  const previousValue = layout.style.getPropertyValue(propertyName);
  const previousPriority = layout.style.getPropertyPriority(propertyName);
  const controller = new AbortController();
  const min = Number(spacing.min);
  const max = Number(spacing.max);

  function updateSpacing() {
    const pixels = spacing.valueAsNumber;

    if (!Number.isFinite(pixels) || pixels < min || pixels > max) {
      return;
    }

    layout.style.setProperty(propertyName, `${pixels}px`);
  }

  spacing.addEventListener("input", updateSpacing, {
    signal: controller.signal,
  });
  updateSpacing();

  return function cleanup() {
    if (controller.signal.aborted) {
      return;
    }

    controller.abort();

    if (previousValue === "") {
      layout.style.removeProperty(propertyName);
    } else {
      layout.style.setProperty(propertyName, previousValue, previousPriority);
    }
  };
}

// Mount once per view; call cleanupSpacing() before removing it.
const cleanupSpacing = mountSpacingControl();

Use style.setProperty() on the narrowest relevant element. The range control supplies a number between 0 and 32, and the script adds px only after validation. Run the script after the HTML exists, for example as a module. [8]

getComputedStyle(layout).getPropertyValue("--layout-gap") reads the current value; style.getPropertyValue() reads only the inline declaration. removeProperty() removes the inline override. Avoid unnecessarily interleaving geometry reads and style writes during frequent updates. [8][9]

The function returns a cleanup callback: call it when unmounting the view. It removes the listener and restores the previous inline declaration, including its priority. Check values 0, 16 and 32, missing elements, and mounting again after cleanup. [11]

Can a CSS variable be a media-query breakpoint?

<div class="catalog">
  <article>First product</article>
  <article>Second product</article>
</div>
@layer defaults, application;

@layer defaults {
  .catalog {
    --catalog-gap: 1rem;

    display: grid;
    gap: var(--catalog-gap);
  }
}

@layer application {
  @media (min-width: 48rem) {
    .catalog {
      --catalog-gap: 2rem;

      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }
}

var() substitutes values in declarations, not selectors or @media conditions. Instead of @media (min-width: var(--breakpoint)), use a regular breakpoint and override tokens inside the rule. [1][3]

The catalog has a 1rem gap on small screens and 2rem from 48rem; the application layer wins over defaults for normal declarations. To share breakpoints with application code, generate CSS from shared configuration at build time rather than trying to read var() in a query.

A scalable CSS system starts with role-based tokens, not a growing list of global variables. Local scope customizes components, explicit themes control inheritance, and @property is useful when type validation or interpolation matters. A var() fallback cannot replace a correct token contract.

Tools for this topic

CSS CSS Variables Custom Properties Design Tokens CSS Themes CSS Cascade CSS Property API CSS Animation

Frequently asked questions

Do CSS variables replace Sass?

Not entirely. Custom properties operate in the browser and participate in the cascade; Sass can still generate rules and breakpoints at build time.

Is :root required?

No. Declare global tokens on :root and local tokens at the nearest component or theme boundary.

Will var() fix an invalid color?

No, not when the token exists but its substituted value is invalid for color. Consider @property with <color> syntax. [3][7]

Does @property scope a variable to a component?

No. Registration is document-wide; inherits: false changes inheritance, not registration scope. [6]

Sources and references

  1. W3C, CSS Custom Properties for Cascading Variables↩1↩2↩3↩4↩5↩6↩7↩8
  2. MDN, Using CSS custom properties↩1↩2
  3. MDN, var()↩1↩2↩3↩4↩5
  4. MDN, color-scheme↩1↩2
  5. MDN, prefers-color-scheme↩1↩2
  6. W3C, CSS Properties and Values API Level 1↩1↩2↩3↩4↩5
  7. MDN, @property↩1↩2↩3↩4↩5
  8. MDN, CSSStyleDeclaration.setProperty()↩1↩2
  9. MDN, getComputedStyle()↩
  10. MDN, CSS error handling↩1↩2↩3
  11. MDN, EventTarget.addEventListener()↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning