Using CSS Custom Properties for Theme Colors: Scoping, Fallbacks, and Pitfalls
Learn how to define, scope, and safely use CSS custom properties with fallback values, plus common mistakes to avoid.
02 Mar 2026, 07:19 UTC

Using CSS Custom Properties for Theme Colors
Start by defining a variable on an element that acts as a theme root, then reference it elsewhere with var(--name, fallback). The variable inherits down the DOM tree and is scoped to the subtree where it is set.
Worked example
:root {
--primary-color: #0066cc; /* default theme */
}
.card {
background: var(--primary-color, #ccc);
padding: 1rem;
border-radius: 4px;
}
/* Dark theme override */
.dark {
--primary-color: #003366;
}
In the markup:
<div class="card">Light card</div>
<div class="card dark">Dark card</div>
The .card rule uses var(--primary-color, #ccc). If --primary-color is defined on the element or inherited, that value is used; otherwise the fallback #ccc applies. Because --primary-color is set on :root, all cards inherit the light value unless a parent element with class dark resets it, demonstrating scoping and inheritance.
Limits and common mistakes
- Cannot use in selectors or property names: Writing
div[var(--attr)] {}orvar(--prop): value;is invalid syntax and is ignored. - Fallback only for undefined variables: If a variable is set but its value is invalid for the target property (e.g.,
--primary-color: 12px;used where a color is expected), the whole property becomes invalid and the fallback is not applied. - Overuse can bloat CSS: Defining a variable for every single value increases file size and makes it harder to see the final computed value in the rule set.
- Case‑sensitivity:
--Primary-Colorand--primary-colorare different properties.
How to verify
- Open the page in Chrome or Firefox DevTools.
- Select an element that uses
var(--primary-color). - In the Computed tab, locate the resolved value of the property (e.g.,
background-color). - Edit the variable value in the Styles pane (e.g., change
--primary-coloron:root) and watch the computed value update live. - To test the fallback, remove the variable definition from
:rootand observe that the property falls back to#ccc.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.