CSS Custom Properties

by Kuligaposten 2026-08-21

CSS variables let you name a value once and reuse it everywhere — including at runtime.

CSS Custom Properties

CSS custom properties — usually called "CSS variables" — let you define a value once and reuse it throughout a stylesheet. Unlike Sass variables, they're a real part of the CSS language, which means they're evaluated in the browser and can change at runtime.

Basic syntax

A custom property is any property name that starts with --. You read it back with var().

:root {
  --brand-color: #6366f1;
  --spacing-unit: 8px;
}

.button {
  background: var(--brand-color);
  padding: calc(var(--spacing-unit) * 2);
}

Fallback values

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

.card {
  border-radius: var(--card-radius, 8px);
}

Scoping

Custom properties cascade like any other property. Defining one on :root makes it globally available, but you can also scope it to a component so different instances get different values:

.theme-dark {
  --surface: #18181b;
  --text: #f4f4f5;
}

.theme-light {
  --surface: #ffffff;
  --text: #18181b;
}

.panel {
  background: var(--surface);
  color: var(--text);
}

Wrap a section of the page in .theme-dark or .theme-light and every .panel inside it picks up the right colors automatically — no duplicated rules needed.

Changing them with JavaScript

Because custom properties are resolved at runtime, JavaScript can update them directly and the browser repaints immediately:

document.documentElement.style.setProperty("--brand-color", "#f43f5e");

This is a common trick for building a theme switcher or a settings panel without shipping a separate stylesheet per theme.

Why not just use Sass variables?

Sass variables are compiled away — by the time CSS reaches the browser, they're just static values baked into the file. Custom properties stay alive, so they:

  • Respond to media queries and container queries.
  • Can be read and written from JavaScript.
  • Cascade and can be overridden per element, just like color or font-size.

Use Sass variables for build-time constants that never change. Use CSS custom properties for anything that varies by theme, state, or user preference.

Back to Home