CSS Variables Coming to a Browser Near You

If you’ve not been hiding under a rock for the last few years, you’ll know one of the major reasons people love preprocessors like Sass is that they bring variables to CSS. No more find and replace to change colours, font sizes and the like, we just assign these via helpfully named variables like “darkred” (that after a few iterations somehow has tuned a lovely shade of blue).

These variables however, as helpful as they are, are simply syntactic sugar. Before they’re served to the browser, they’ve already been turned back into plain old CSS. But genuine CSS variables (or more correctly known as custom properties) are making their way into browsers today. But custom properties aren’t just Sass variables in the browser, they follow the rules of cascading and can be manipulated via JavaScript in the DOM.

slides [https://www.slideshare.net/secret/JIgU7O3Uy9MitB]

CSS variables have recently gone from “coming soon” to “stable implementation” in Chrome, Firefox, Opera and Safari, with Edge perhaps not far behind.

 

One of the major reasons people love preprocessors like Sass is that they bring variables to CSS. No more find and replace to change colours, font sizes and the like, we just assign these via helpfully named variables.

 

Before they’re served to the browser, however, these variables have already been turned back into plain CSS. Genuine CSS variables (more correctly known as custom properties) are making their way into browsers today, follow the rules of cascading and can be manipulated via JavaScript in the DOM.

10 years of SASS has shown us that it is effective and powerful, but have their limitations, including having scope issues and requiring compilation.

 

CSS sometimes requires the repetition of code in multiple places, making tweaking the code difficult and open to error. An example is using a sitewide colour scheme.

 

CSS frameworks can make this worse, as the framework itself has to be edited. Preprocessors help, but add an extra processing step.

 

CSS variables allow the developer to define values that can be used throughout a document, and apply them using custom properties.

 

Being properties, they follow the cascade and enable inheritance. That should mean less work.

 

A side benefit is that CSS variables typically add semantic information, making CSS files easier to read and edit.

Best practice for using CSS variables is still a work in progress. Some glitches will occur.

 

Browser support is wide but not yet universal. In particular, we should lobby Edge to support them.

 

Custom property syntax has evolved (the prefix was var- in earlier specs, but changed to –), which could lead to confusion for a while yet.

 

CSS variables won’t kill off preprocessors – Sass and the like have features that aren’t in the spec and can’t be achieved with CSS variables.