Creating customisable themes with CSS Variables

Explore the new powers arriving on the web with CSS Variables in both CSS and JavaScript!

The tutorial

As developers the ability to store common values for reuse is extremely valuable, it saves time in both authoring and maintaining a codebase. This is why you'll find variables a key part of any CSS pre-processor, such as Sass or LESS. The CSS Variables spec finally introduces this ability natively to CSS and there's now a good level of browser support available to start putting them into use.

However, you may have been thinking, since CSS pre-processors have variables already and are so prevalent these days, what's the big deal? Fuelled by this I decided to take a look at what CSS Variables will offer developers beyond simply storing values for reuse.

There are two interesting aspects I've found lately when working with CSS Variables. Firstly they, like all CSS, are susceptible to the cascade. This means that you can give a CSS Variable a new value and it only effect the children of that CSS rule in the document.

The second aspect is that CSS Variables can be accessed and updated by JavaScript at runtime. This means that through user actions, you could update a the styles on your site easily through a small amount of JavaScript. In this case, I'm going to look at using colour inputs to instantly update the theme of a website.

Demo by Adam Onishi