CssHandler: CSS + Variables

Please don't consider using this project anymore - it is old and out of date. Use something like SASS or LESS instead.

It's been more than three and a half years since Rory Blyth said "screw standards - let's add variable support to CSS right this minute." In retrospect, adding variables to CSS seems obvious; everyone is asking about it. There have even been one or two other .Net solutions developed, though Rory's solution has remained my favorite. With CSS2 barely working and CSS3 not addressing the issue, those of us who are tired of repeating ourselves throughout our CSS files have no choice but to take matters into our own hands.

With that in mind I set out to update Rory's code. Not that there was anything wrong with it in the first place, of course (this is where I try to tactfully avoid being drawn as a jerkasaurus in one of Rory's comics), but Rory did whip the code up for a PADNUG meeting and that was about 3.5 million years ago (give or take many orders of magnitude). It was time to bring the CssHandler into 2007! Conveniently right before 2008.

Lo and behold, someone else had beat me to it. Gabe Moothart had already uploaded the CssHandler to CodePlex, and even improved upon it. While Rory's code originally only allowed variable declarations & references and stripped comments, Gabe's version also resolved application-relative paths (e.g.: "~/blah/blah.gif") into browser friendly paths. I had further goals in mind though, and Gabe was kind enough to add me onto the project.

With my updates complete, I am now proud to present...

CssHandler 1.0

Features:

Bugs fixed:

Example:

The HTML references "styles.css", which looks like:

As seen above, "styles.css" references "styles2.css" via the @import statement, which looks like:

The CssHandler then:

  1. Intercepts the browser's request for "styles.css".
  2. Resolves the two URLs that are using application relative paths.
  3. Replaces the @import directive with the text from "styles2.css".
  4. Strips all comments from the CSS.
  5. Replaces all referenced variables with their defined values.
  6. Compresses most of the CSS's white-space.
  7. Renders the following to the browser:

I hope you find it as useful as I have. Many thanks to Rory Blyth and Gabe Moothart. Hopefully CSS4 will add variables and we'll never have to use this again!

Visit the project's CodePlex site to download.

Update (Dec. 2, 2007): Rory has posted and given his blessing, so to speak. Thanks Rory!