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.

:root {
  --primary-color: #2a90e7;
}

body {
  background-color: var(--primary-color);
}

a {
  color: var(--primary-color);
}

Variables can be used anywhere you would normally write a string. In the simple example below, CSS variables are used within a calc, as a fallback font, and also to define part of an rgba colour.

:root {
  --default-padding: 10px;
  --fallback-font: 'Courier New';
  --primary-color: 0, 0, 0;
}

h1 {
  padding: calc(var(--default-padding) * 2);
  font-family: 'NotARealFont', var(--fallback-font);
  color: rgba(var(--primary-color), 0.5);
}

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.

window.getComputedStyle(document.documentElement).getPropertyValue('--primary-color');

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!

Other recent posts: