CSS: A New Star-HTML hack

CSS: A New Star-HTML hack

Perhaps you already know of this article: #IEroot — Targeting IE Using Conditional Comments and Just One Stylesheet. If so, you should have told more people. I have been using the Star-HTML hack for some time as it was an easy way to serve my CSS to IE or non-IE browsers. Well, IE 7 fixed their code and killed the use of it to serve specific styles. This new fix, apparently posted by Hiroki Chalfant uses IE’s Conditional Comments to serve a bit of additional mark-up to the page. While this does add unnecessary mark-up, you would still need to do something to serve different styles. The main advantage to this is you can still write everything in a single style sheet. Very cool.

The basic idea is that you use Conditional Comments to put a wrapper around your site. This is only seen by IE. All others simply display your page as they should. The tag is written just after the body tag and closed before you close your body. Very easy. In fact, here is the code for your HTML:

<body> <!––[if IE]><div id="IEroot">< ![endif]––> <p>Whatever other elements for your page.</p> <!––[if IE]></div>< ![endif]––> </body>

That is it. Now, you can write your styles like this:

/* all browsers make border red */ #p { border : 2px solid red; } /* all browsers see this, but only IE thinks #IEroot exists as an element and makes border blue */ #IEroot #p { border-color : blue; }

The nice thing about this approach is you can further customize the Conditional Comments to suit your needs. Better is unless the IE team decides to remove Conditional Comments, you have a future-proof fix. At most, you might need to modify the way the Conditional Comments are written should that ever change. But compare that to having to go back through hundreds of lines of CSS which are rendered useless because the IE team fixes existing bugs we regularly exploit to make our pages work.

I only wish I knew of this a few years ago.


blog comments powered by Disqus