Free, independent guides since 2010

Code

CSS custom properties (variables) explained

How CSS custom properties work: defining and using variables, fallbacks, scope, theming and dark mode, and why they make a website easier to maintain.

<guide section="Code" type="guide" read="1 min"/>

Change your brand colour on a site with hundreds of CSS rules and you will understand why custom properties exist. They let you define a value once and use it everywhere. They build on the basics in what is CSS.

Defining and using variables

CSS
:root {
  --brand: #6e0a0a;
  --paper: #faf6f0;
  --space: 1rem;
  --radius: 12px;
}
.button {
  background: var(--brand);
  padding: var(--space) calc(var(--space) * 2);
  border-radius: var(--radius);
}

Custom property names start with two dashes and are case-sensitive.

Fallbacks

CSS
.card { color: var(--card-text, #222); }

If --card-text is not defined, #222 is used.

Scope: variables cascade

CSS
.alert { --accent: #b77714; border-left: 4px solid var(--accent); }
.alert.error { --accent: #a12a1d; }

Changing a variable on a component changes it for everything inside. This is how this website gives each section its own colour: one class sets --sec-bg and --sec-fg, and every component inside follows.

Dark mode in a few lines

CSS
@media (prefers-color-scheme: dark) {
  :root { --paper: #181414; --ink: #f2ece6; }
}
body { background: var(--paper); color: var(--ink); }

More in designing a dark mode.

Changing variables with JavaScript

JavaScript
document.documentElement.style.setProperty('--brand', '#2b5a86');

Good practice

  • Name variables by purpose (--text-muted) rather than by value (--grey-5) for things that may change.
  • Keep a small set: colours, font sizes, spacing scale, radius, shadows.
  • Document them at the top of your stylesheet.

Variables are the foundation of a small design system – see design systems for small sites.

Frequently asked questions

Do CSS variables work in all browsers?

Yes, all current browsers support custom properties. Only very old browsers such as Internet Explorer lack support.

What is the difference with Sass variables?

Sass variables are replaced when the CSS is compiled. CSS custom properties live in the browser, so they can change at runtime, per element or with JavaScript.