CSS Variable Fallback
CSS Variable Fallback
CSS variables are increasingly used in front-end development. But when we use CSS variables, the value of the CSS variable may be empty for some reason, especially if the value of this CSS variable is controlled by JavaScript.
Here is an example:
.message__bubble {
max-width: calc(100% - var(--actions-width));
}
The variable --actions-width
is used in the CSS function calc()
, and its value is controlled by JavaScript. Suppose JavaScript fails to set the value of --actions-width
for some reason. This will cause calc()
to calculate an invalid max-width
value, which may cause unexpected layout problems.
We can avoid this in advance by setting a fallback value for --actions-width
.
.message__bubble {
max-width: calc(100% - var(--actions-width, 70px));
}
If the variable is not defined, the fallback 70px
will be used. This approach can be used to avoid setting variables that may fail (for example: from Javascript).