DEV Community

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

Posted on • Edited on

2 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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...

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️