Future CSS: variables and calculations

The W3C came under a lot of heavy flak last year for being slow, cumbersome, bureaucratic, etc; there were calls for a CSS2.2 (which I seconded) which rounded up all the existing implemented features, and for the CSS Working Group to be disbanded — a lighter, alternative task force, the CSS Eleven, was set up to try and make sense of it all. But as we’ve heard nothing from them in the six months since they were set up, I think the Eleven have found it’s not as easy as it looks.

The CSS WG has a new chair now, including the passionate Daniel Glazman, and it seems to be refocused and refreshed, which is good news; in his latest blog post, he says that the WG is aiming for RECs, RECs, RECs. If that’s the case, maybe we can start to get excited.

One thing that Glazman mentions the CSS WG are looking at is of particular interest to me as I was preparing to write a long post about them: variable constants. In short, assigning CSS values to variables so you can reuse them throughout your style sheets. For example:

@define { key_color: #f00; }

h1 {
color: $key_color;
border-bottom: 1px solid $key_color;
}

Note: The syntax used above is my own invention; the actual syntax has not been decided upon yet. This would allow you to use the same color for many different elements, but only have to update it once if a change was being made. You could use the same syntax for dimensions, content strings, borders, paddings… I’m sure you can imagine plenty of test cases.

This would also be useful when used in conjunction with the proposed calc() function, which would allow you to perform simple calculations. This would help us with that common problem of mixing percentage widths with fixed padding and margins; for example:

@define { box_padding: 100px; }

div {
padding: $box_padding;
width: calc(100% - $box_padding);
}

There are some dissenting voices that say that this complicates CSS and pushes it towards a programming language; I see their point, but for me it’s just too useful to disregard, and having done some thinking about this recently I don’t believe it needs to get any more complex than what you see here; plus, of course, you’d still be able to make great websites without using variables, as we do at the moment!