conditional comments hacks ie hack ie6 ie7 ie8 ie9

As long as I can remember, developers have always been trying to target IE one way or another. Thanks to the wonders of modern technology, there have been multiple ways to pull this off.

I guess I really haven’t been keeping up with the latest frontend trends (doh!), as I’ve just recently discovered this very elegant solution circa 2008 offered by Paul Irish, which sticks a class on the body tag using proprietary conditional IE tags (no JavaScript magic needed here!):

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

No need for creating multiple stylesheets for each version of IE (that makes extra network requests… boo)! Now you can add adjustments to your main stylesheet just as you would with CSS hacks, except now you’re doing it in a not-so-hacky way.

For instance, if you have some peculiar CSS quirk in IE6, you simply apply a fix like this:

.some-element { width: 200px; }         /* standards-based browsers */
.ie6 .some-element { width: 160px; }  /* elegant ie6 fix! */

The old way: CSS hacks

Previously I considered some CSS hacks the most elegant solution, but that was in the days when IE6/7 ruled. You can see that the following CSS hack gets really unruly for IE8 (that hack thanks to David Bloom):

.some-element {
    width: 200px;                /* standards-based browsers */
    /* some yet-to-be-determined IE9 hack goes here */
    width /*\**/: 180px\9        /* targets IE8 standards mode */
    *width: 170px;               /* targets IE7/IE6 */
    _width: 160px;               /* targets IE6 */

This works, but becomes quite difficult to maintain and understand. And it just creates a need for someone to find yet another hack for each new version of IE that’s released. By using the IE conditional comments to add a class to the body tag, we can accomplish the same result in a way that is easier to read and maintain and is dead simple to update when a new version of IE is released:

.some-element { width: 200px; }
.ie9 .some-element { width: 190px; }
.ie8 .some-element { width: 180px; }
.ie7 .some-element { width: 170px; }
.ie6 .some-element { width: 160px; }


Conditional comments block downloads: Stoyan Stefanov’s concerns over using this pattern

comments powered by Disqus