CSS variables

According to the apocrypha there was a support for CSS variables in some browsers three years ago. Unfortunately I haven’t found a way how to verify it. caniuse.com is silent, there are only blog posts1 about it. At the moment the only browser which supports CSS variables is Firefox. According to Sara Soueidan Safari landed support for them last week:

And according to Chrome Platform Status CSS variables are being implemented at the moment, or at least that’s how I interpret that green-yellow color. Microsoft’s Edge is on the way too.

How to use CSS Variables?

That’s a great question. Basic usage is simple. At one place coder defines a variable and then uses it in the rest of the code. There are no loops or control structures at the moment, hopefully there will be in the future so we can ditch preprocessors2.

First thing that comes to my mind how to use CSS variables are colors. Every design has limited color selection which can be used on a website. So instead of writing all the time specific code to every element we can name that color and use it instead:

There is an alternative which I find quite awful:

The reason why I think it’s awful is because groupings like this one would appear throughout the code quite often. If there was something I learned at the graduate school it’s that you ought not write Spaghetti code. It was in a class about middleware but it applies here too. This is Spaghetti code.

The second place where I would use CSS variables are sizes. Although reasonably short class name would do performance-wise similarly as the usage of CSS variables. Let’s have an example A, the current way:

And Example B, CSS variables:

Similarly this could be to applied to a number of CSS properties, although it might be a bit weird when it comes to font-family .

Conclusion

There is a great future for the variables in CSS especially if CSS adopts some control structures besides media queries. Currently they are not widely adopted so usage is limited. But the best use case I haven’t mentioned here yet are semantic CSS stylesheets. Computers don’t need them but coders do.

If we can use CSS variables we don’t have to keep in mind all the places that need to be changed. We can name our own colors instead of calculating in head that hexadecimal code looks like after a rendering. We can do all this with preprocessors but I still have some reservations towards them, mainly I don’t know implement them in my workflow yet.

  1. http://css3.bradshawenterprises.com/blog/css-variables/, and http://www.webmonkey.com/2012/06/css-variables-webkit-brings-the-css-jackalope-to-life/
  2. I think I am too much too hopeful that we will get rid of the in the near future. I just dislike debugging complex stuff in them.