← Lessons

quiz vs the machine

Silver1100

Frontend

CSS Custom Properties for Theming

Define variables once and cascade theme values through your whole UI.

4 min read · intro · beat Silver to climb

Variables that cascade

CSS custom properties, written with two leading dashes, are real variables that live in the cascade. You define them on a selector and read them with the var function.

  • Declare a property like color brand on the root selector.
  • Read it anywhere with var of that name, optionally with a fallback.
  • Because they cascade and inherit, a value set on a parent flows to all descendants.

Why they suit theming

Unlike preprocessor variables that vanish at build time, custom properties are live at runtime. Change one value and every dependent rule updates instantly.

  • Define a base palette on the root, then override a subset under a theme class such as theme dark.
  • Toggling that class on the body switches the entire UI without rewriting components.
  • JavaScript can read and set them too, so users can pick custom colors.

A small set of well named variables becomes the single source of truth for your theme.

Key idea

CSS custom properties are runtime variables that cascade, so overriding a few on a theme class restyles the whole UI instantly.

Check yourself

Answer to earn rating on the learn ladder.

1. How do CSS custom properties differ from preprocessor variables?

2. How do you read a custom property in CSS?