Tony Bogdanov Tony Bogdanov - 6 months ago 15
CSS Question

How to use commas in a CSS variable fallback?

How can one use commas in the fallback value of a CSS variable?

E.g. this is fine:

var(--color, #f00)
, but this is weird
var(--font-body, Verdana, sans-serif)
.

The idea is to be able to set a
font-family
using a variable with a fallback value of say
Verdana, sans-serif
.

Answer

The below is an extract from the W3C spec: (emphasis is mine)

Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(--foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value.

As you can see from the above statement, if your intention is to set Verdana, sans-serif as fallback value when --font-body is not defined then the syntax given in question is expected to work. It does not require any quotes as per spec.

I don't have a browser that supports CSS variables and hence I couldn't test the following code but it should work based on the spec:

.component .item1 {
  --font-body: Arial;
  font-family: var(--font-body, Verdana, sans-serif); 
  /* should result in font-family: Arial */
}
.component .item2 {
  font-family: var(--font-body, Verdana, sans-serif);
  /* should result in font-family: Verdana, sans-serif */
}
<div class=component>
  <p class=item1>Arial
  <p class=item2>Verdana, sans-serif
</div>