Fallback Values for CSS Variables
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What Happens if a Variable Is Not Defined
If var() references a custom property that was never declared anywhere in scope, the property using it fails to apply at all - it does not silently fall back to some default CSS value on its own.
Providing a Fallback Value
.btn {
background: var(--brand-color, #1d4ed8);
}The second argument to var() is used only if --brand-color is not defined anywhere in scope - a safety net for components that might be dropped into a page that has not set up that variable.
When Fallbacks Are Genuinely Useful
- Building a reusable component library where consuming projects may or may not define certain theme variables.
- Writing defensive base styles that should still look reasonable even if a later theme file fails to load.
- Providing a safe default while a design system's variables are still being finalized.
Chaining Multiple Fallbacks
.btn {
background: var(--btn-color, var(--brand-color, #1d4ed8));
}Fallbacks can be nested: this tries a very specific --btn-color first, falls back to a more general --brand-color next, and finally falls back to a hardcoded value if neither is defined anywhere.
A Different Case: An Invalid Value
A fallback only helps when a variable is completely undefined. If a variable is defined but holds an invalid value for that property (for example, text where a color is expected), the property is treated as if it were never set at all - the fallback in var() does not catch this case, since the variable itself is technically defined.