CSS Variables (Custom Properties)
Custom properties let you define reusable values once and reference them throughout a stylesheet, making themes and consistent spacing far easier to maintain.
Defining and Using Variables
Custom properties are typically defined on :root so they're available globally, then referenced anywhere with var(). Unlike preprocessor variables (like Sass), CSS custom properties are live in the browser and can even be changed with JavaScript.
:root {
--primary-color: #00cc44;
--text-color: #1a1a1a;
--spacing-unit: 8px;
--radius: 6px;
}
.btn {
background: var(--primary-color);
color: white;
padding: calc(var(--spacing-unit) * 2);
border-radius: var(--radius);
}
Providing Fallbacks
var() accepts a second argument as a fallback value, used if the custom property hasn't been defined — useful for components meant to work even without a surrounding theme.
Common Mistakes
- Forgetting the double dash prefix when declaring a custom property, e.g. writing primary-color instead of --primary-color.
- Defining variables too locally when they're meant to be global, instead of on :root.
- Confusing CSS custom properties with Sass/Less variables — custom properties are resolved live in the browser, not compiled away ahead of time.
- Not providing a fallback value for a variable used in a reusable component that might be dropped into a page without the expected theme variables.
Professional Tip
Because custom properties are live in the browser, you can override them inside a specific selector — like a `.dark-theme` class — to instantly re-theme every element that references them, with no duplicated rules.
Your Turn
Define --primary-color, --spacing-unit, and --radius on :root, then use them across a button and a card component. Add a .dark-theme class that overrides --primary-color and confirm both components update.
Mini Quiz
How do you reference a CSS custom property named --primary-color in a declaration?
var() function reads a custom property's value at the point it's used, and can optionally take a fallback as a second argument.