Variables in CSS

Simon has a feature request for CSS3, which is the oft-heard “please let me define variables in my stylesheets” complaint. I’ve thought this more than once (and I’m sure I brought it up somewhere on a mailing list for discussion, too; I thought it was css-discuss, but I can’t find it in the archive). So, I thought, that’d be an interesting little Javascript hack, wouldn’t it; have JS look at the stylesheet rules and fix ones where you’ve used a “user defined variable”. Ah, but no. After some testing, both Mozilla and IE just don’t make invalid rules (or rulesets) available to the DOM at all. Given this stylesheet as the first and only in the document:

h1 { font-size: 1.2em; color: red; }
@media screen {
  pre { color: blue; }
}
@define {
  reddish: #f00;
}
h2 { font-size: 1.1em; color: &reddish; }
h3 { font-size: 1.0em; color: red; }

p>You’d expect document.styleSheets[0].cssRules (or ...rules for IE) to contain 5 entries, right, one for each of the rules? Nuh-uh. Walking through the rules and displaying .cssText for each (in Moz; displaying stylesheet.cssText in IE), the stylesheet looks like this:

h1 { font-size: 1.2em; color: red; }
@media screen { 
   pre { color: blue; } 
}
h2 { font-size: 1.1em; }
h3 { font-size: 1em; color: red; }

Note how both the entire invalid @define ruleset and the invalid color: &reddish rule have both been removed. No trace of them at all. So the only way I can think of making this work is to use XMLHttpRequest() (or MSXML) to grab external stylesheets, document.getElementsByTagName(‘style’) to grab inline stylesheets, and parse them yourself. For something which will only work in very modern browsers (and not anything without XMLHttpRequest or an equivalent) with Javascript turned on, that’s way, way too hard, especially since half the point of CSS is to be cross-browser and not require scripting. Since this isn’t get implemented in CSS, looks like server-side parsing is the way to go. Bah. As Simon points out from the w3c-style discussion, it breaks compatibility in older browsers, although I can’t see why you can’t do:

h1 {
    color: red;
    color: &myred;
}

since the latter declaration is ignored by non-supporting browsers, just like all other CSS stuff.

None

More in the discussion (powered by webmentions)

  • (no mentions, yet.)