How do CSS custom properties (variables) work?
Define reusable values with --name syntax on :root, then reference them anywhere with var(--name).
CSS
Overview
CSS custom properties (often called CSS variables) let you store values in one place and reuse them throughout your stylesheet. Unlike preprocessor variables (Sass/Less), they are live in the browser, can be changed with JavaScript, and respect the cascade.
Key Points
- •Declare on `:root` to make a variable global: `--color-primary: #3b82f6;`
- •Use with `var()`: `color: var(--color-primary);`
- •`var()` accepts a fallback: `var(--color-accent, hotpink)` used when the variable is unset.
- •Variables are scoped: a re-declaration inside a selector overrides for that subtree only.
- •JavaScript can read/write CSS variables with `element.style.setProperty("--name", value)`.
Examples
Define and use global variables
css:root {
--color-primary: #3b82f6;
--color-bg: #0f172a;
--spacing-md: 1rem;
--radius: 8px;
}
.button {
background: var(--color-primary);
padding: var(--spacing-md) calc(var(--spacing-md) * 2);
border-radius: var(--radius);
}Scoped override (dark mode component)
css.card {
--card-bg: #1e293b;
background: var(--card-bg);
}
.card.highlighted {
--card-bg: #1d4ed8; /* overrides just for highlighted cards */
}Dark mode via a single class toggle
css:root {
--bg: #ffffff;
--text: #0f172a;
}
[data-theme="dark"] {
--bg: #0f172a;
--text: #f8fafc;
}
body { background: var(--bg); color: var(--text); }Update a variable from JavaScript
javascriptdocument.documentElement.style.setProperty('--color-primary', '#f59e0b');Pro Tip
Use CSS variables for your design tokens (colours, spacing, radii, font sizes). Changing one value in `:root` instantly updates every element that references it.