CSS Variables (Custom Properties)

I watched the talk of Guil Hernandez from CSSconf EU 2017. I found out that CSS variables work really easily and are a powerful tool.

A simple example

To set a variable’s value:

To retrieve the variable’s value:

To see it in action, look at this CodePen:

CSS variables need to be defined within a scope. :root is a pseudo class that represents the <html> element. It is the top level scope. Let’s see what we can do with scopes.

An example using scopes

The variable can be overridden in a different scope. For example, in this code the variable ‘color’ is ‘blue’ in the class ‘.wrapper’ and ‘red’ everywhere else:

Javascript example

The advantage of CSS variables, compared to Sass or Less variables, which are precompiled, is that the variable can be changed on the fly. You can for instance change a variable from your javascript code:

<DOM element>.style.setProperty(‘ <var name>’, ‘<var value>’);

Wrapping up

CSS variables are globally supported at 72.16% by browsers:


Thanks for reading this article. CSS offers lots of new features; let me know in the comments if you would like me to post again on this topic.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.