16 July 2008

A quick go at CSS preprocessing in JavaScript

Chris Heilmann's post today about CSSPP, a PHP preprocessor for CSS, set the old brain going so I decided to knock up a quick proof of concept (FF only) in JavaScript doing some of the same stuff. Namely, it has very quickly hacked nested rule parsing and a form of the replacement variables feature.

Currently you have to specify your CSS for processing in a script tag with a particular type...

<script type="text/csspp">
.red {
 border: 2px solid red;
 h2 {
  background: #933;
 p {
  background: $derek$;
.blue {

 border: 2px solid blue;
 background: $other$;

...and the variables are retrieved from a JavaScript object by name...

<script type="text/javascript">
var cssVars = {
 derek: '#FCC',
 other: '#CCF'

Obviously a JavaScript implementation like this would slow down the user experience and wouldn't have any of the snazzy caching features of a server-side version but it might be useful if you're hacking a bit of CSS and don't have a PHP server handy.