QuestionsHTML/CSS

CSS custom properties & theming

Custom PropertiesMediumHTML/CSS

How do CSS variables differ from Sass variables? Use them to implement a light/dark theme.

What it tests

Whether you know custom properties are live, inherited, runtime values — not compile-time text.

Approach & answer

Custom properties (CSS variables) are declared as --name: value on a selector and read with var(--name, fallback). Unlike Sass/Less variables — which are compile-time text substitutions that vanish from the output — custom properties are LIVE and part of the cascade: they inherit to descendants, can be overridden per-selector, respond to media queries, and can be read and written at runtime from JavaScript (element.style.setProperty('--x', …)). That runtime nature is what makes them ideal for theming: define your palette once on :root, then override the same variable names under a [data-theme='dark'] selector (or inside a prefers-color-scheme media query). Every component that references var(--bg) instantly re-themes when the variable changes — no rebuild, no duplicated rule sets. They cascade like any property, so you can also scope a variable to a subtree (e.g. a card that redefines --accent). Gotchas: they are case-sensitive, only usable in property VALUES (not selectors or property names), and invalid values fall back to the declared fallback or the inherited/initial value. Pair with calc() for derived values.

Use this technique when

Theming (light/dark), design tokens shared across components, and any value you want to tweak at runtime from JS.

References

html