CSS Variables: Custom Properties and var() Explained
Your brand color appears in buttons, links, borders and headings. Without variables you repeat #0e7490 twenty times, and a redesign becomes a search-and-replace job. Custom properties, usually called CSS variables, let you name a value once and reuse it.
Defining and using
A custom property is any property whose name starts with two hyphens. You read it with var():
:root {
--brand: #0e7490;
--space: 1rem;
}
.button {
background: var(--brand);
padding: calc(var(--space) / 2) var(--space);
}
:root selects the <html> element, so properties defined there are available everywhere. Names are case-sensitive: --Brand and --brand are two different variables.
They cascade and inherit
Unlike variables in preprocessors such as Sass, custom properties are real CSS properties. They follow the cascade and are inherited by descendants. That means you can override a variable for one part of the page, and everything inside that part picks up the new value:
.card.danger { --brand: #be123c; }
Every var(--brand) inside a .danger card now resolves to red, with no other rule changed. This is how themes and component variants are built. The example defines a brand color on :root, overrides it in one card and prints the color each button ended up with.
Expected page text
Save Delete Save button: rgb(14, 116, 144) Delete button: rgb(190, 18, 60) --space on :root: 12px
Fallback values
var(--accent, teal) uses teal if --accent is not defined. The fallback can itself be another var(). Fallbacks are handy in reusable components that may land on pages that never set the variable.
Changing variables from JavaScript
Because they are live properties, a script can update one and the whole page responds: document.documentElement.style.setProperty('--brand', '#7c3aed'). Dark mode switches often work this way, toggling a class that redefines a handful of color variables.
Common mistakes
- Forgetting the double hyphen:
-brandorbrandis not a custom property. - Expecting
var()to work in selectors or media query conditions; it only works in property values. - Mixing up case:
var(--Brand)does not read--brand.
Summary
- Define with
--name: value;, read withvar(--name). - They inherit, so redefining one on a container restyles everything inside.
var(--name, fallback)covers undefined variables.
Quiz: Custom properties