DEV Community

Cover image for Optional CSS transform with CSS variables
Yair Even Or
Yair Even Or

Posted on • Edited on

Optional CSS transform with CSS variables

Assuming you have a component which has a default transform property value(s) and can also have additional ones, which are optional, then logically it should be written as so:

.component {
             |-- default ---| |-- optional --|
  transform: translate(100px) var(--transform);
}
Enter fullscreen mode Exit fullscreen mode

But...It does not work as intended if the --transform variable is not defined.

I am unsure why, but it can be easily fixed using this trick:

.component {
  transform: translate(100px) var(--transform, );
}
Enter fullscreen mode Exit fullscreen mode

Did you notice? There is a fallback defined to nothing: (, )

W3 Spec:

In an exception to the usual comma elision rules, which require commas to be omitted when theyโ€™re not separating values, a bare comma, with nothing following it, must be treated as valid in var(), indicating an empty fallback value.

Demo:

https://jsbin.com/vejusaj/edit?html,css,output

Top comments (3)

Collapse
 
afif profile image
Temani Afif

you can see the why in (7) : dev.to/afif/what-no-one-told-you-a... :)

Collapse
 
yaireo profile image
Yair Even Or

Ha, I know that a variable can be empty, but I didn't view it as a related thing to this scenario because here the fallback is empty and not the variable itself, but I guess both cases root from the same origin

Collapse
 
afif profile image
Temani Afif

Yes, both accept a "declaration value" (w3.org/TR/css-variables-1/#using-v...) so they follow the same rule defined here: w3.org/TR/css-syntax-3/#typedef-de...