What are variables in CSS?

Variables in CSS are custom properties: named values you define once, such as --brand: #2b4bff;, and reuse anywhere with var(--brand). Unlike preprocessor variables, they live in the browser, follow the cascade and inheritance, and can change at runtime with media queries, themes, component states or JavaScript.

Defining and using

:root { --brand: #2b4bff; --space: 1rem; --radius: 8px; }
.btn { background: var(--brand); padding: var(--space); border-radius: var(--radius); }
  • Names start with -- and are case-sensitive.
  • :root makes them global; defining them on a selector scopes them to that subtree.
  • Fallbacks: var(--accent, hotpink).

What makes them powerful

  • Theming: redefine a few variables under [data-theme="dark"] or @media (prefers-color-scheme: dark), and the whole UI updates.
  • Component variants: .btn.danger { --brand: #e11d48; } changes only that button.
  • Responsive values: change --space inside a media query.
  • JavaScript bridge: el.style.setProperty("--x", e.clientX + "px") for cursor effects and animations without recalculating styles in JS.
  • Calculations: calc(var(--space) * 2).

Good practice

Use them as design tokens (colors, spacing, radii, z-index scale), name them by purpose (--color-text-muted) rather than value (--gray-500) at the component level.

Interview tip

Contrast them with Sass $variables: compile-time and static versus runtime and cascading.

Code example

html
1<style>
2 :root { --brand: #2b4bff; --bg: #fff8ec; --text: #0b1020; --space: 12px; --radius: 10px; }
3 [data-theme="dark"] { --bg: #0b1020; --text: #f8fafc; --brand: #ffd84d; }
4 body { font-family: system-ui; background: var(--bg); color: var(--text); padding: var(--space); }
5 .btn {
6 background: var(--brand); color: var(--bg); border: 0;
7 padding: var(--space) calc(var(--space) * 2); border-radius: var(--radius); font-weight: 700;
8 }
9 .btn.danger { --brand: #e11d48; } /* scoped override */
10 .spot { width: 100%; height: 80px; margin-top: 12px; border-radius: var(--radius);
11 background: radial-gradient(circle at var(--x, 50%) 50%, var(--brand), transparent 40%); }
12</style>
13<button class="btn" id="theme">Toggle theme</button>
14<button class="btn danger">Danger</button>
15<div class="spot" id="spot">Move your mouse here</div>
16<script>
17 document.getElementById("theme").onclick = () => {
18 const root = document.documentElement;
19 root.dataset.theme = root.dataset.theme === "dark" ? "light" : "dark";
20 };
21 const spot = document.getElementById("spot");
22 spot.addEventListener("pointermove", (e) => spot.style.setProperty("--x", e.offsetX + "px"));
23</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app