Another way to hack CSS for IE (nicely?)

After some #IEroot inspiration at positioniseverything.net and some help from here, I’ve come up with yet another approach to paritioning CSS rules based on the browser. Using this technique you can get rid of the * html hack and the need for a separate IE 7 CSS file.

I liked how positioniseverything suggested using conditional comments to make different IDed wrapper divs (eg <div id=ie6>..page..</div>) but I didn’t like all those extra divs around. So why not just put the id on the body?

With this technique, there will be no extra elements in the dom since I’ve placed the conditional comments so that there always will only be one body element. Some may argue that all those extra comments are ugly, but hey it validates and does not incur any extra semantics or accessibility headaches of extra elements.

Here is what I came up with:

    1 <html>
    2   <head>
    3     <title>IE conditional comments test</title>
    4     <style type=text/css media=screen>
    5       #ie7 p { color: red; }
    6       #ie6 p { color: green; }
    7       #ieOther p { color: blue; }
    8       #nonIE p { color: black; }
    9     </style>
   10   </head>
   11
   12   <!–[if gte IE 7]><body id=”ie7″><![endif]–>
   13
   14   <!–[if IE 6]><body id=”ie6″><![endif]–>
   15
   16   <!–[if lt IE 6]><body id=”ieOther”><![endif]–>
   17
   18
   19   <!–[if !IE]><!–><body id=nonIE><!–<![endif]–>
   20
   21     <div>
   22       Testing which version of IE (or non-IE) you have.
   23     </div>
   24
   25     <div>
   26       <script type=text/javascript charset=utf-8>
   27         var body = document.body;
   28         document.write( body.id =  + body.id );
   29       </script>
   30     </div>
   31
   32     <p>
   33       Colored text. Red = IE 7, Green = IE 6,
   34       Blue &lt; IE6, Black = not IE
   35     </p>
   36
   37   </body>
   38 </html>

Try it out here

Close
E-mail It