…or… <html>’s conditional classes

From what I’ve seen a good number of developers these days are split between conditional stylesheets and css hacks.

You’re used to seeing this:

But probably also plenty of this:

CSS hacks to target specific browsers stay where the rest of your styles are, but they certainly don’t validate. For sometime now, the standards community has rallied around conditional stylesheets as a solution to the validation problem.

There are a few problems with it though:

Here’s my proposed solution:

Using the same conditional comments, we’re just conditionally adding an extra class onto the html tag. This allows us to keep our browser-specific css in the same file:

Plus it totally validates and works in all browsers.

(Hat tip to Paul Hammond and Adam McIntyre for being s-m-r-t.)

2010.05.07: Patrick O’Neill put this technique on some steroids. I rather like it. See below:

Doug Avery of Viget points out he prefers to use this technique on the HTML tag, freeing the body tag for dynamic classes. That works just fine. I later changed all my sites to use it on HTML instead of body, actually… Also it combo’s really well with the Avoiding the FOUC v3.0 technique as well as Modernizr.

You fancy something different?

2010.05.07: Oh sheesh ya’ll. Mat Marquis pointed out the code would leave a page <body>-less in IE10, etc. (Well not really because IE would auto-construct a body tag, but anyway…) Some gt later and we’re good.

2010.05.20: Turns out IE conditionals around css files for IE6 can slow down your page load time in IE8! Crazy, right? The solution here avoids that, as does forcing IE to edge rendering.

2010.06.08: And then… Rob Larsen points out that when these conditional classes are applied to the HTML element, it doesn’t block. No empty comment necessary. I think that’s a new winner.