CSS Constants
(Page 1 of 7 )
One feature designers often wished they had with style sheets are constants –- the chance to define something once and reuse it over and over in the style sheet document. This article shows some techniques for how to achieve that and discusses their pros and cons.
A constant nagging
When reading CSS related forums or mailing lists, you’ll sooner or later find someone asking how they can define a “constant” in CSS –- something to define once in the CSS document and reuse throughout it.
There are several reasons why there are no constants in CSS:
- The CSS specifications didn’t plan for any constants, variables, loops or conditions simply because CSS is there to describe the visual presentation of a document, not programming logic. The same applies to HTML –- there are no variables, constants, loops and conditions. Its job is to describe what a certain text is, within this document, regardless of what variables were sent to it.
- CSS is “executed” on the client -– the browser. Browsers on slower computers already have problems rendering CSS properly. Fixed positioning and big background graphics can cause delays and flickering. What would happen if they had to process the “CSS logic” on top of that?
- Any scripting on the client side is, however low, a security threat and allows for exploits. Microsoft Internet Explorer’s ability to embed Javascript in CSS files proved that.
However, CSS constants could be something very handy indeed.
Possible Uses
CSS constants would make it easier to turn style guides into CSS and allow for smaller style sheet documents without much repetition. You define the colors once and add the constant name every time you want to use it.
/* Company Colours */
$blue=’#369’;
$green=’#363’;
$lgreen=’#cfc’;
[…]
ul#navigation{ background:$blue;
color:#fff;
}
h1{ border-bottom:1px solid $green;
}
White-labelling and redesign would be a breeze; all you need to change is the constants, and all the styles comply with the new colors. No more search and replace sessions, and the inevitable setting that escaped them.
Another option would be to define often used styles and keep the document shorter.
$boxstyles=’background:#ccc;border-top:1px solid #eee;
border-left:1px solid #eee; border-right:1px solid #aaa;
border-bottom:1px solid #aaa;padding:.5em;margin:.5em 0’;
h1{ $boxstyles
color:#000;
}
div#extras div { $boxstyles
font-size:80%;
}
Since CSS does not allow for that, we need to find a way around the problem. One is to use what CSS does provide us with.
Next: The CSS standard compliant approach >>
More Style Sheets Articles
More By Chris Heilmann