Fri 15 May

CSS Tip: Conditional classes

You’re building a website. You write your stylesheet, testing as you go in Firefox, Safari, Chrome, Opera and IE8. It’s all good.

Then you open Internet Explorer 6 and 7. It’s a mess in there. You’ve got some work to do. But how are you going to make sure only IE6 or 7 sees your fixes without putting all manner of ugly hacks into your CSS?

It’s remarkably simple. Microsoft have their own special “conditional comments”, which are special HTML comments that only IE can see. Other browsers just ignore them. Paul Hammond turned them to his advantage, bunging a class="IE" on the body tag. I’ve taken it a step further here:

<!--[if IE 6]><body class="IE6"><![endif]-->
<!--[if IE 7]><body class="IE7"><![endif]-->
<!--[if IE 8]><body class="IE8"><![endif]-->
<!--[if !IE]>--><body><!--<![endif]-->

Those first three body tags are aimed at the different versions of Internet Explorer I have to deal with. The last one is ignored by IE and picked up by all the other browsers out there. As a result, you can do things like this:

div.floatylight {
float: left;
margin-left: 12px;
}
/* This triggers the IE6 doubled-margin bug */
.IE6 div.floatylight {
margin-left: 6px;
}

Brilliant! I haven’t had to use the .IE8 class yet, but it’s still young.

EEEK! A fundamental flaw! (15 April 2010)

I’ve noticed a rather fundamental flaw in my use of <body> above. If someone arrives using a version of IE we haven’t catered for (e.g. IE5 or the new IE9), they won’t get a body tag.

So to cater for this, I suggest you add a div as the first child of the body instead:

<body>
<!--[if IE 6]><div class="IE6"><![endif]-->
<!--[if IE 7]><div class="IE7"><![endif]-->
<!--[if IE 8]><div class="IE8"><![endif]-->

<!-- Put the rest of the page here -->

<!--[if IE 8]></div><![endif]-->
<!--[if IE 7]></div><![endif]-->
<!--[if IE 6]></div><![endif]-->
</body>

All the same benefits we had before, but a lot more bulletproof.