Software Development

CSS variables - tools to simplify changing a color of website

February 25, 2016
Rafał Grądziel

Every developer who has developed any webpage has the same problem: a change of primary color implies changes in many CSS files and careful find/replace operations for all occurrences of specific value.

Some of us are already using CSS pre-compiler libraries (like Less), which allows us using variables on CSS level in our code.

Less can be embedded strictly using client-side pre-compilation, without a need to compute it on application server (like PHP or ASP scripts), which would definitely make it easier to start using Less stylesheets in our project.

Variables are defined using syntax @variable1: value123, for example:

// file: styles.less
@baseColor: #aabbcc;

.box {
  color: @baseColor;

will be complied into:

.box {
  color: #aabbcc;

On client-side we need to include files like this:

<!— our Less stylesheet -->
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<!-- Less.js script which will handle client-side pre-compilation -->
<script src="less.js" type="text/javascript"></script>

However, if we don’t want to add extra stress to client’s browser and we have performance in mind, Less authors recommend pre-compiling using node.js or other third party tools.

It is an interesting solution, but works only on runtime level and changes cannot be applied during application life cycle without stylesheets recompilation.

Google Chrome browser, starting from version 49, has added support for CSS variables.

:root {
  --main-color: red;

#foo h1 {
  color: var(--main-color);

Access to CSS variables is also possible from JavaScript level:

var styles = getComputedStyle(document.documentElement);
var value = String(styles.getPropertyValue('--main-color')).trim();
// value = "red"

What is interesting: discussion and works on this part of CSS standard have been started in 2012, but – as we see – its implementation is going slowly and the document is still just a draft:

Browsers currently supporting CSS variables:

  • Chrome 49
  • Firefox 42
  • Safari 9.1 and iOS Safari 9.3

(no known roadmap for Microsoft Edge or Opera)

Full list of browser support for CSS variables:

I think it is worth to keep an eye on the changes in this topic and check how fast other browsers will also add support for this CSS feature.