CSS Variable Fallback

CSS variables are gaining more and more usage in web design. There is a method that we can apply to use them in a way that doesn’t break the experience, in case the CSS variable value was empty for some reason.

This is particularly useful when feeding the value of a CSS variable via Javascript. Here is an example:

.message__bubble {
max-width: calc(100% - var(--actions-width));

The variable --actions-width is being used within the calc() function and its value is coming from Javascript. Let’s suppose that Javascript failed for some reason, what will happen? The max-width will compute to none.

We can avoid that ahead of time and add a fallback value to the var().

.message__bubble {
max-width: calc(100% - var(--actions-width, 70px));

That way, if the variable isn’t defined, the fallback 70px will be used. This approach can be used in case there is a possibility that the variable might fail (e.g: coming from Javascript).

Examples and use cases

An invalid CSS variable

.element {
background-color: var(--brand-color, lightblue);

Support Defensive CSS

Do you like the content? You can buy me a cup of coffee. Thank you!

About the author

Ahmad Shadeed

Ahmad is a UX designer and front-end developer from Palestine. He enjoys working on challenging design and front-end development projects. He wrote a book on debugging CSS, writes extensively on CSS, Accessibility, and RTL (right to left) text styling.