How to Use CSS Custom Properties (Variables) (2026)
By Rui Barreira · Last updated: 18 June 2026
CSS custom properties — commonly called CSS variables — let you define a value once and reuse it throughout a stylesheet. Change it in one place and every rule that references it updates automatically. They are native to CSS, require no build tools, and cascade like any other property, which means you can override them inside media queries, selectors, or even inline styles.
Syntax and Scope
Custom properties are declared with a double-dash prefix and are case-sensitive. They must be declared inside a selector; :root is the conventional choice for global tokens.
:root {
--color-primary: #3b82f6;
--spacing-md: 1rem;
--font-size-base: 16px;
}
.button {
background: var(--color-primary);
padding: var(--spacing-md);
font-size: var(--font-size-base);
}A variable defined on a child element is only visible to that element and its descendants — the same scoping rules as CSS inheritance. This makes component-level theming straightforward without class name conflicts.
| Feature | CSS Custom Property | Sass/Less Variable |
|---|---|---|
| Resolved at | Runtime (browser) | Compile time |
| Cascades / inherits | Yes | No |
| Overridable in media queries | Yes | No |
| Readable via JavaScript | Yes — getComputedStyle | No (compiled away) |
| Build tool required | No | Yes |
Fallback Values and JavaScript Access
The var() function accepts an optional fallback as the second argument. If the variable is not defined, the fallback is used instead of the property being invalid.
color: var(--color-accent, #6366f1);You can also read and write custom properties from JavaScript, which enables runtime theming without reloading any CSS:
// Read
const value = getComputedStyle(document.documentElement)
.getPropertyValue('--color-primary').trim();
// Write
document.documentElement.style.setProperty('--color-primary', '#ef4444');This is the foundation of theme-switching (light/dark mode) and dynamic design tokens — values computed from user preferences or API data can be injected directly into the cascade.
Practical Patterns
Group related tokens under a naming convention (--color-*, --space-*, --radius-*) to keep the token set navigable. For dark mode, redefine tokens inside a prefers-color-scheme media query or a [data-theme="dark"] selector — the rest of the stylesheet stays untouched. For component-level overrides, redeclare only the tokens you need on the component root element rather than duplicating full rule sets.
Use the CSS Variables Generator to build a token set visually and copy the ready-to-paste :root block in seconds.
Frequently Asked Questions
- Is this tool free?
- Yes — completely free, no signup required. All processing happens in your browser.
- Does the tool work offline?
- Once loaded, most features work without an internet connection since everything runs client-side.