Cody G. Henshaw

Hacking the WWW

CSS Variables in Firefox - AKA Variable Verbosity

So, I saw this tweet from Chris Heilmann.

Awesome… maybe. I grabbed a fresh copy of FF Nightly and got to playing. The MDN Docs give a couple of examples… Here’s another.

So, in this example, we don’t use any variables at all. We do, however, repeat the color #bada55 FOUR times. I’m primarily a backend developer, and this redundancy kind of gives me the chills… Thanks to CSS Variables, however, we can eliminate some of this repetition. Here’s another example, this time using variables… (Keep in mind, this will only work in Firefox 29 Nightly at the moment.)

Pretty cool, right? It’s not exactly shorter, but it is nice not having to remember hex values or color names…

The title of this post included something along the lines of “Variable Verbosity”, and that’s not to discount the addition of variable support into browsers. I think it’s awesome that the web is moving forward, just don’t go throwing away your Sass or Less install just yet (obviously these tools do WAY more than just add variables). Here’s how variables look when you use preprocessors vs. firefox’s implementation (merely to show differences in implementation).

Sass

1
2
3
4
$foo: #000000;
.bar {
  background: $foo;
}

Less

1
2
3
4
@foo: #000000;
.bar {
  background: @foo;
}

FF 29

1
2
3
4
5
6
7
/* invalid if not scoped */
:root {
  var-foo: #000000;
}
.bar {
  background: var(foo);
}

Well, that about does it for this article. As you can see, the native implementation is much longer than the preprocessing variants, but hey, at least we’re moving forward. I’ll mess around with it a bit more, and see if I can come up with some cool stuff that shows that these are actually useful (beyond the evident use). If I’ve got any errors (which is not unlikely), please shoot me a note @CodyHenshaw on twitter. Thanks for stopping by!

December 17, 2013 - Update:

So, after publishing this, something was brought to my attention. I had totally disregarded the concept of scope in this post, which is definitely one of the things that Mozilla did right with their variables. Scoped variables are helpful because they allow you to “silo” variables for use in specific parts of an application, or even declare them globally to be used throughout an application (in this case, a stylesheet). So, without further ado, let’s get to scope.

Scoping variables is trivial in both the Mozilla implementation, and with CSS preprocessors, like Sass. Here’s what it looks like with CSS (again, only works in FF 29 at the time of writing).

Here’s how you do it with Sass… (You could also define a mixin with vars, and use them wherever you need to)

Either method works. Just wanted to throw this out there to show the scope capabilities of both native CSS and Sass. If someone wants to give me a Less example, I’d be happy to put it out there too. Thanks.