W3C releases CSS 3 variables draft

A specification for using variables in CSS has reached the first standardisation milestone.

Anyone who has created a large style sheet can appreciate the monotony of having to type out the same colour hex code over and over again in their style sheets. After a process that began in 2008, the first Working Draft from the W3C has appeared that details CSS 3's variable module specification.

It has been a long time coming for CSS variables; it is promoted as the first feature mentioned on the website of LESS, a popular style sheet language that has extended CSS to give developers access to desired features, such as mixins and variables.

And while this is undoubtedly good news for CSS, something about the syntax is not right. Feast your eyes on it:

:root {

var-header-color: #06c;


h1 { background-color: var(header-color); }

The prefix var- is used to define the variable, and the var function is used to invoke them. Variables can be defined in different scopes by being set on different selectors, and allows for overloading, such as:

:root { var-color: blue; }

div { var-color: green; }

#alert { var-color: red; }

* { color: var(color); }

<p>I inherited blue from the root element!</p>

<div>I got green set directly on me!</div>

<div id='alert'>

While I got red set directly on me!

<p>I'm red too, because of inheritance!</p>


It will also be possible to define variables based on other variables.

<one><two><three /></two></one>

one { var-foo: 10px; }

two { var-bar: calc(var(foo) + 10px); }

three { var-foo: calc(var(bar) + 10px); }

The values variables can be arbitrary, meaning that it will be possible for an invalid value to be passed with a variable. In this case, the property will have a value of invalid attached to it, the default value for the property will be used. For instance:

:root { var-not-a-color: 20px; }

p { background-color: red; }

p { background-color: var(not-a-color); }

This will give a background colour value of "transparent" — background colour's default value. The property's value is set at the time that the variable is calculated, so previous set values are discarded.

As the above examples show, the syntax isn't all that terrible; it's just non-obvious, and a move from the norm.

I do think however, that the way LESS does it would be better.

@color: #4D926F;

#header { color: @color;}

h2 { color: @color;}

Here begins the ponderous process towards standardisation for CSS variables, and the wait for browser vendors to implement it. I wouldn't be giving up LESS anytime soon; it has more features and works today.