After reading a post on The Cafes about the lack of dynamics in the CSS language, I found myself inspired to do something about it. It became clear that something had to be done and that we couldn’t wait for the W3C to come up with a new standard and browser vendors to incorporate them.
There were two things I wanted to enrich the CSS language with:
To make it work, I created an HttpHandler for ASP.NET that is able to parse these two new features and apply them to the stylesheet. It does not interfere with any CSS standards because everything is handled by the server.
Here is an example of a .css file that uses these new capabilities.
define BACKCOLOR = #00FFFF;
define FORECOLOR = pink;
define TOTALWIDTH = 550;
define RIGHTWIDTH = browser == "IE" & version >= 6 ? "150px" : "170px";
define LEFTWIDTH = TOTALWIDTH / 2 + "px";
This will then be outputted as this standard compliant stylesheet:
All the lines beginning with "define" will be treated as a variable declaration, parsed and then deleted from the parsed stylesheet. Notice the two variable names "browser" and "version". Those two variables are built in properties that return the browser name and major version number respectively.
There are two versions of the HttpHandler – one to use if you can control the IIS and one if you can’t.
If you are able to let the IIS send .css files to the ASP.NET engine you should download the CssHandler.cs file below and add it to the App_Code folder and then add the following to the web.config:
<add type="CssHandler" verb="*" path="*.css" />
If you can’t access the IIS, you need to download the CssHandler.ashx below and then call that file while passing the .css file as a query string in the URL like this:
<link rel="stylesheet" type="text/css" href="csshandler.ashx?path=style.css" />
Total feature list
This is the total feature list of the handler:
- Add variables to CSS (feature)
- Use scripting capabilities (feature)
- Server and client side caching (performance)
- Cache dependant of the source .css file (performance)
- Whitespace and comment removal (performance)
- Works only on .css files (security)
- Blocks the System namespace (security)
Word of caution
Because the scripting language is pure C#, it also means that you have to take injection attacks into account. I’ve already made sure that any scripting using anything in the System namespace will be rejected. That means that you can’t use any System.File.IO commands or anything else that has the word “System.” in it. That eliminate probably 99% of the obvious attack surface, but it is not totally secure.