Markup Conditionals
I loathe conditional comments and browser targeted code. But there comes a time when you have to support an old and out dated browser (I’m looking in the direction of IE6 at the moment). So what do you do? You have to make it look the same and function the same as other browsers. You also shouldn’t use browser hacks to target them. I’ve touched on this subject before and figured conditional comments were the best route to go. Even if I don’t like them.
I’ve recently started working with a new company and have picked up on some of the bright things they do. I’m not sure why I never thought of this before since it seems so simple (and I can’t take credit for it).
Let say you have your standard body element and a few other things on a page:
<body>
<div>
<p>Some text</p>
</div>
</body>
Typically to target the paragraph element for, say IE6, you might use a simple hack like the underscore hack. So you might write some CSS like so:
p {
width:150px;
_width:200px;
}
I mean you might do that, some other hack or you might use conditional comments to provide a style sheet just for IE6. I’m sure you’ve seen code like this before:
<!--[if IE 6]>
<link rel="stylesheet" type="text/css"
href="ie6.css" />
<![endif]-->
That’s all fine and dandy, but do you see what you did there? I did and I don’t like it. You’ve just created another HTTP request. Shame on you. And to think about how many CSS rules are typically in a file like that? 10? 50? It also creates a maintenance headache. You’ve now split up rules for one element into two files. Yes yes I know that is what the cascade is for… But you could make it easier on yourself and people that come behind you.
What I’ve found is to use conditional comments to specify a class on the body element when the browser is IE6 or 7 or even 8.
So taking our markup example from above I’ve modified it to have conditional comments in it:
<!--[if IE 6]><body class="IE6"><![endif]-->
<!--[if !IE ]><!--><body><!--<![endif]-->
<div>
<p>Some text</p>
</div>
</body>
You’ll need all those extra comments to make the page valid. It is also pretty easy to add as many combinations as you like as long as they can be read by the browsers…
And our CSS from above:
p {
width:150px;
}
.IE6 p {
width:200px;
}
Of course this only works with IE but really you shouldn’t need this at all since you build awesome websites that are already cross-browser compatible, right? And there is no chance ever that a client will want a site to be usable in IE5.5, right?

