CSS, is the heart of any web application today. Writing cross browser CSS is really a hell of an art and including CSS files selectively and writing CSS hacks that will work out in one browser but wont in other is also a tedious job.
Anyway, I have come up with a tiny CSS handler , which might be handy in terms of loading multiple CSS for different browsers, removing extraneous characters that can help reduce file size and do some caching on the browser end.
At the end of post , I have given the files to download, but before that lets see how can we put it in our project.
First of all , add it to your .aspx or .master file.
<link rel="Stylesheet" href="StyleHandler.axd" type="text/css" />
Then , add the handler to the httpHanlders section in web.config
<add verb="*" path="StyleHandler.axd" type="CssHandler" validate="false"/>
Of course, the CssHandler.cs should be under App_code. Also, validate=false means the underlying handler file wont be verified for its existence(Ex. there is no physical existence of StyleHandler.axd). Finally, you need to include a tiny xml file to the web project, that will have the browser to CSS mappings.
<cssMappings> <add browser="all" file="default1.css|default2.css"/> <add browser="ie*" file="allie.css" /> <add browser="firefox*" file="allfirefox.css" /> </cssMappings>
"all" means the CSS will be included for all browser types. ie*, firefox* means the CSS file will be used for all versions of that particular browser. Similarly, when specific browser number is used (Ex.ie7), the corresponding CSS file will only be included for that specific type of browser.In some scenarios, it is necessary that we have customized CSS for different version of the same browser, in that case ie* and ie7 distinction is useful. "|" is used for multiple CSS files that will be combined for a given browser type. You can also add "safari" and other known browsers that you wish to target CSS for, but you need to be sure of the name which is passed in HttpRequest for a particular browser to put it in mapping file, as the handler compares mapping entry with Request.Browser property values.
Additionally, the handler does a basic compression , by removing comments, newlines and tabs that makes browser feel happy.
To see , how the code works or to give a try, download it here
Updated Jan 27, 2008 : Added Gzip compression