CSS Variables

One big limitation of CSS when building any kind of site is that it is hard to easily change common values, such as colours and font sizes. This in part led to the proliferation of preprocessors such as SASS and LESS, which support the use of variables. The latest CSS spec set out to fix this by adding CSS variables. The good news is that they are natively supported by all modern browsers, and you can start using them right away.

Usage

If you have worked with variables in SASS or LESS, then CSS Variables will feel quite familiar to you. Variables are defined by prepending them with --. Once defined, they are referenced using var. Variables can be defined inside any block. As per the Cascading in Cascading Style Sheets, an element’s variable is available to all of its children.

To define a variable globally, it is best to define it on the :root pseudo-element. In practice, this ends up referencing the html element, but using :root is a good way of maintaining obvious separation.

In the basic example below, we define our primary colour in the :root element and reference it later using var. Now if we want to change the primary colour across the site, we only need to change it in one place, rather than everywhere across the code.

Accessing from Javascript

One feature that CSS variables offer, which preprocessors cannot, is the ability to easily access these variables from Javascript. To do this, simple call getPropertyStyle on the element’s computed style, with the name of the variable you want. If you have defined your variables on root, then the element you want is document.documentElement.

Should I use variables?

If you only need to support the latest browsers, then you should start using them right away. Take a look at CanIUse’s CSS Variables Support Table to see if it makes sense for you. They will immediately make your CSS a lot easier to work with. You will wonder how you ever wrote CSS without them!