Free beginner tutorial

CSS Custom Properties (Variables)

CSS custom properties let you store values once and reuse them throughout a stylesheet. They are often called CSS variables and are useful for colors, spacing, type scales and component themes.

Quick answer: Declare a custom property with a name beginning with two dashes, such as --brand-color. Read its value inside a declaration with var(--brand-color).

Declare and reuse a custom property

Place shared values on :root when they should be available across the document. A value can then be reused by many selectors.

:root {
  --brand-color: #176b9a;
  --space-medium: 1rem;
}

.button {
  background-color: var(--brand-color);
  padding: var(--space-medium);
}

Unlike a preprocessor variable, a CSS custom property exists in the browser’s CSS cascade. You can inspect or change it in developer tools, and its value can depend on the element where it is defined.

Use a fallback value

The second argument to var() is a fallback. The browser uses it when the referenced custom property has no usable value for that element.

.card {
  border-color: var(--card-border, #ccd5dc);
}

A fallback helps a component continue to render if a theme value has not been set. It does not validate a value that is present but invalid for the CSS property.

Override values for a component or theme

Custom properties follow the cascade and usually inherit. Define a new value on a nested component to adapt its appearance while keeping the same component rules.

:root {
  --surface: #ffffff;
  --text-color: #202a32;
}

.dark-panel {
  --surface: #202a32;
  --text-color: #ffffff;
}

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

The values on .dark-panel apply to that element and its descendants unless another matching rule overrides them. Consider contrast when creating alternate themes.

Common custom property mistakes

  • Custom property names are case-sensitive, so --brand and --Brand are different.
  • Use the variable inside a property value; it cannot replace a selector or property name.
  • Check that the final value suits the property where it is used.

CSS custom property questions

Why do custom property names start with two hyphens?

The double-hyphen prefix identifies a CSS custom property, for example --page-gutter. The name is authored by the page and does not create a built-in CSS property.

Do CSS custom properties inherit?

By default, custom properties inherit. A descendant can use a value defined on an ancestor, while a more specific local declaration can override it.

Practice: make a small theme

Create custom properties for a brand color, text color and spacing value. Use them on a button and a card. Then override the surface and text colors on a second card and check that both themes remain readable.