What You'll Learn
You'll master how to reference CSS custom properties with fallback values, ensuring your designs gracefully degrade when variables are undefined or invalid.
Understanding var() with Fallbacks
The var() function retrieves the value of a custom property, but what happens if that property doesn't exist or contains an invalid value? This is where fallback values come in.
The var() function accepts a second argument—a fallback that the browser uses if the custom property is unavailable:
.element {
color: var(--brand-color, #3498db);
}
If --brand-color isn't defined anywhere in scope, the element's color falls back to #3498db.
Why Fallbacks Matter
Think of fallbacks like safety nets. When building themes or component libraries, you can't always guarantee a custom property will be set. Fallbacks ensure your design doesn't break:
:root {
--primary-color: #2c3e50;
}
.button {
/* If --button-bg is missing, try --primary-color */
/* If that's also missing, use gray */
background: var(--button-bg, var(--primary-color, gray));
}
You can chain fallbacks by nesting var() calls, creating multiple layers of safety.
Dynamic Theming Pattern
Fallbacks shine in theming scenarios where components might exist outside their expected context:
.card {
/* Use component-specific variable, or fall back to global theme */
padding: var(--card-spacing, var(--spacing-md, 1rem));
background: var(--card-bg, var(--surface-color, white));
}
This pattern allows components to be flexible—they'll use local values when available, but won't break when moved to different contexts.
Invalid Values Trigger Fallbacks
If a custom property exists but contains an invalid value for the property where it's used, the browser treats it as if the variable doesn't exist and uses the fallback.
Key Takeaway: Always provide fallback values in var() for robust, maintainable CSS that handles undefined or invalid custom properties gracefully—essential for theming and component-based design.