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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay