CSS custom properties for cascading variables

  • June 5, 2018
  • CSS

Preprocessors like Less and Sass have helped over the past few years to keep development CSS codebases simple, organised and maintainable. One of the most used features in preprocessors is the ability to use variables in the stylesheet which was not possible natively in CSS. Now it is possible to use CSS custom properties in native CSS with support across most browsers apart from IE.

Why bother with CSS variables?

The problem with stylesheets is that they can become large, bloated and very confusing to maintain and often these stylesheets have repeating colours, fonts, borders and other values which are used over and over. As W3 say:

Large documents or applications (and even small ones) can contain quite a bit of CSS. Many of the values in the CSS file will be duplicate data; for example, a site may establish a color scheme and reuse three or four colors throughout the site. Altering this data can be difficult and error-prone, since it’s scattered throughout the CSS file (and possibly across multiple files), and may not be amenable to Find-and-Replace.

With CSS variables you could set your colours, fonts, padding, margins only once and then re-use that one variable over and over. Then if your font changes for example, then you need to make only one amend and then it will cascade throughout your stylesheet.

The syntax for CSS variables

At time of writing the CSS custom properties for cascading variables is a W3C candidate recommendation since December 2015. As mentioned above it has good browser support.

To get started you will first need to do the custom property part which looks like this:

--primary-color: #999;

A custom property always starts with two dashes and then assign a value, in this case “primary-color”. It is worth noting that custom properties are case sensitive so, “PRIMARY-color” would be different to “primary-color” but both are valid to use.

The second part is then using your custom property using the var() function, which looks like this:

var(--primary-color)

So an example snippet of code would be:

:root{
--primary-color: #444;
}

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

In the above example we have just said at the root level we have a CSS custom property called primary color of a value of #444, then for our heading one we want to apply the variable primary color which is declared at the root level which will turn our heading one that color.

Fallback value

If your cascading variable hasn’t been declared or isn’t valid then there is a fallback option, which could look like:

h1{
color: var(--primary-color, black);
}

Anything between the first comma and the end of the function is considered a fallback value for your cascading variable.

Resources

If you would like to learn more about CSS variables and how they differ to preprocessors ones then here is a few additional resources below:


Did you enjoy this? Hire me