Weeee, CSS variables just landed in WebKit, this is pretty exciting!
Unfortunately I couldn't see them in action in WebKit nightly (must be something I'm missing), but they're here and here to stay. I know there are "purists" that say that stuff like variables has no place in the language and we don't really understand CSS, it's different, etc, etc. But once W3C has a modest proposal and one major engine is implementing variables, then this is where we're headed. And I personally applaud this direction.
Syntax
So the basic idea, according to W3C is this. There are two steps: you declare a variable (together with a value assignment) and then you use it.
This is a declaration of the variable my-color
. It's a global variable (defined under :root
).
:root { var-my-color: #fad; }
Then you use it like:
.thing { color: var(my-color); }
And the .thing
gets the color #fad
.
In WebKit
Webkit currently uses a -webkit
vendor prefix which makes the whole thing more verbose:
:root { -webkit-var-my-color: #fad; } .thing { color: -webkit-var(my-color); }
There are many examples for your browsing pleasure in the form of test files in WebKit's repo
Future
It's here. And it's only getting better. There's a dev draft of the CSS variables proposal which talks about using $
instead of var()
to refer to a variable, which is so much nicer. Spoken like a true php'ied, eh? 🙂
:root { var-my-color: #fad; } .thing { color: $my-color; }
Exciting times!
Comments? Feedback? Find me on Twitter, Mastodon, Bluesky, LinkedIn, Threads