Improved Internet Explorer Targeting through Body Classes

May 07, 2010

I've seen a couple variations of Paul Irish's solution to target styles to versions of Internet Explorer and found them all lacking in one critical aspect: the ability to target IEs less than or equal to a given version number.

With conditional comments, you can target version groups:

<!--[if lte IE 7]> ... <![endif]-->
<!--[if gte IE 6]> ... <![endif]-->

With inline CSS hacks, you can target styles to IE6 and IE7 simultaneously:

p { color:red; }
p { *color:blue; }

But when you use the aforementioned solution:

<!--[if lt IE 7 ]> <body class="ie6 "> <![endif]-->
<!--[if IE 7 ]>    <body class="ie7 "> <![endif]-->
<!--[if IE 8 ]>    <body class="ie8 "> <![endif]--> 
<!--[if !IE]><!--> <body> <!--<![endif]-->

You need to use the following to target styles to IE6 and IE7:

p { color:red; }
.ie6 p, .ie7 p { color:red; }

While this isn't a big deal, it still bugs me.

Room for Improvement

I have an devised extension of Paul's solution that works around this issue (that also takes the upcoming IE9 into account, of course):

<!--[if lt IE 7]>  <body class="ie ie6 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 7]>     <body class="ie ie7 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 8]>     <body class="ie ie8 lte9 lte8">      <![endif]-->
<!--[if IE 9]>     <body class="ie ie9 lte9">           <![endif]-->
<!--[if gt IE 9]>  <body class="ie">                    <![endif]-->
<!--[if !IE]><!--> <body>                               <!--<![endif]-->

This allows you to target styles in a version-descendant fashion or to all versions of IE at once:

p { color:red; }
.ie p { color:green; }
.lte7 p { color:red; }

You could conceivably add "greater than or equal to" classes as well, but I can't think of a use for it. The only drawback to this approach is that it slightly complicates inheritance (more classes means more chance of conflicting rules), but with a modicum of caution, I don't foresee that being a major issue.

Update: Mat Marquis tweeted an improvement to the improvement. Things just keep getting better.