How to Set Fallback Value for CSS Variable
Use the
var() function with a second argument to set a fallback value for a CSS variable, like var(--my-color, blue). This fallback is used if the variable --my-color is not defined or invalid.Syntax
The syntax for using a CSS variable with a fallback value is var(--variable-name, fallback-value). The first part --variable-name is the custom property you want to use. The second part fallback-value is the value the browser uses if the variable is missing or invalid.
css
color: var(--text-color, black);Example
This example shows how to use a CSS variable with a fallback color. If --main-bg-color is not set, the background will be lightgray.
css
html {
--main-bg-color: lightblue;
}
body {
background-color: var(--main-bg-color, lightgray);
color: var(--main-text-color, black);
font-family: Arial, sans-serif;
padding: 20px;
}
/* If you comment out the --main-bg-color in html, background becomes lightgray */Output
A page with a light blue background and black text reading normally.
Common Pitfalls
One common mistake is forgetting to provide a fallback value, which can cause the property to be invalid if the variable is missing. Another is using an invalid fallback value or syntax errors inside var(). Also, fallback values only apply if the variable is not set or invalid, not if it is set to an empty string.
css
/* Wrong: no fallback, may cause no color if variable missing */ color: var(--missing-color); /* Right: fallback ensures color is always set */ color: var(--missing-color, red);
Quick Reference
- var(--name, fallback): Use fallback if variable missing
- Fallback can be any valid CSS value
- Fallback only triggers if variable is undefined or invalid
- Use fallbacks to improve robustness and avoid broken styles
Key Takeaways
Use
var(--variable, fallback) to provide a fallback value for CSS variables.Fallback values ensure styles work even if the variable is missing or invalid.
Always provide a fallback to avoid unexpected missing styles.
Fallbacks accept any valid CSS value like colors, sizes, or keywords.
Fallbacks do not apply if the variable is set but empty; handle that separately.