Floating Octothorpe

Using CSS custom properties

Back in 2014 Firefox 31 was the first major browser to support CSS custom properties (variables). Since then most major browser vendors have added support for CSS custom properties, the major exception being Internet Explorer.

What are custom properties?

Prior to CSS custom properties, if you wanted to use a colour multiple times, you would explicitly duplicate the colour. For example:

blockquote {
  color: #ABC123;
  border-left: solid 3px #ABC123;
  padding: 1em;
}

This problem is slightly alleviated by properties being inherited, however large blocks of CSS could often become hard to maintain.

Custom properties allow CSS authors to use arbitrary properties with a -- prefix. These properties can then be referenced using the var function. For example the CSS above could be written as follows:

:root {
  --example-color: #ABC123;
}
blockquote {
  color: var(--example-color);
  border-left: solid 3px var(--example-color);
  padding: 1em;
}

Dynamic CSS

A slightly more complicated example might looks something like this:

:root {
  --accent-hue: 200;
  --accent-color: hsla(var(--accent-hue), 50%, 45%, 1);
  font-family: Helvetica;
}
h1, h2 {
  color: var(--accent-color, blue);
}
a {
  color: var(--accent-color, blue);
}
blockquote {
  border-left: 5px solid var(--accent-color, blue);
  padding: 1em;
  font-style: italic;
}

In the example above --accent-hue is used to control the --accent-color property, which is reference by declarations later on in the style sheet. Because the accent colour is controlled entirely by the custom property, it's easy to dynamically modify the accent colour hue with JavaScript similar to the following:

var new_hue = 100;
document.documentElement.style.setProperty("--accent-hue", new_hue);

The screenshot below shows a demo page using JavaScript to do this:

Example web page using CSS custom properties to dynamically control
colours

What about CSS preprocessors?

At the time of writing CSS preprocessors such as less or Sass are commonly used when working with large style sheets. While CSS custom properties are unlikely to complete replace CSS preprocessors, there is definitely an overlap with problems preprocessors are being used to solve, and what can now be done with the addition of custom properties.

One key point to consider is variables used in custom processors cannot be referenced or modified by a browser after compilation. This means they cannot be dynamically modified by JavaScript or updated based on CSS media queries. Ultimately I suspect custom properties will be used along side preprocessors, however time will tell.

Further reading

If you want to learn more about CSS custom properties I would recommend having a look at the following: