7 December 2009 3:09a Pacific

Browser-specific CSS without Javascript or horrible syntax

by Matt Sherman

So, we all know that browsers have differing levels of CSS support. Working around them can be a pain in the a**, requiring non-standards-based hacks which are very hard to read and debug.

I’d like to write CSS that looks like this:

...etc. Even better:

That’s readable, and isn’t polluted with the –moz stuff or <!—If IE –> or whatever. How to do it? Well, on the server, I simply add a class (or classes) to the <body> tag. It ends up looking like this:

...or...

So, every child of <body> inherits the browser-specific class(es). This allows you to use the readable CSS above.

I implemented this in C# as an extension method on HttpBrowserCapabilities. Like so:

Then, in my master page:

Easy-peasy. I added a bit of cleverness that gives you both “webkit” and “chrome” so you can target the rendering engine and/or the browser. Of course, this could go further, recognizing (say) mobile browsers or operating systems. Give me your ideas in the comments.

You should be able to do similar in PHP or whatever. Hope this helps!

--

PS: One might be tempted to use Javascript/jQuery to achieve the above. But CSS mustn’t depend on JS – we need our pages to degrade gracefully in the absence of JS.

Related: CSS that is scoped only when Javascript is present

--

PPS, using extension methods in your master page may require adding a line to web.config, let me know if you need help

Comments are closed

Tell others

TwitterTweet this page
Digg!Digg this page
TwitterAdd to Google Reader

Experimental! Let me know how it works for you.

Shorten this page's URL

Learn more about the TinyASP URL shortener

ASP.Net jQuery Controls

Implement jQuery effects using familiar ASP.Net server controls. Learn more...

Recent posts

Avoiding “magic strings” in jQuery, C# and ASP.net MVC

Alikewise learnings #1: DIY PR

Sherman’s law of prior knowledge, or, predicting the past

The busiest people at Apple right now…

When “infographics” jump the shark

HTTPS is the least of your problems

Stacking up

Beware the truth-tellers

more...  

About us

ClipperHouse.com is brought to you by Matt Sherman and Fernando Chilvarguer, among others. Contact us here.