Conditional sibling class names for IE patching

Traditionally, web developers have been using either CSS hacks or conditional comments to target different versions of Internet Explorer with CSS fixes. In the last few years more and more people have started using conditional class names, more or less as described by Paul Irish in Conditional Stylesheets vs CSS Hacks? Answer: Neither!.

I’ve always favoured separating IE fixes from the main CSS by putting them in one or sometimes two separate files loaded via conditional comments. However, a valid argument against that is that keeping the patches in the same file as the main CSS increases maintainability since you’re less likely to forget about the patches when updating the main CSS. That problem can be solved by using conditional comments to add class names to the html element depending on which version of IE is used.

The problem is that it can create plenty of HTML bloat since you need to repeat the opening HTML tag—including any attributes it has—for every version of IE that you want to target. So I started thinking that maybe there is a different way. And there is, though it too has its drawbacks. Nevertheless, here’s another way of solving the problem.

Put the comments inside the body element

I wanted to reduce code bloat by avoiding to repeat a tag that has other attributes and/or class names. What I did was insert a new element that is not used for anything else, like this:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Document title</title>
</head>
<body>
<!--[if IE 7]><div class="ie7"></div><![endif]-->
<!--[if IE 8]><div class="ie8"></div><![endif]-->
<!--[if IE 9]><div class="ie9"></div><![endif]-->
	<div id="body">
		<h1>Document title</h1>
	</div>
</body>
</html>

To apply different CSS in a specific version of IE, you use adjacent sibling selectors. Assuming the above document, giving the h1 element different background colours in IE 7-9 would look like this:

.ie7 + div h1 {
	background:#fcc;
}
.ie8 + div h1 {
	background:#cfc;
}
.ie9 + div h1 {
	background:#ccf;
}

Load the Conditional sibling class names demo page in IE 7-9 and see the difference.

The pros and cons

So, why do it this way instead? I think the main advantage is cleaner markup, but there are other pros as well as a couple of cons:

Pros

Cons

I always use a wrapper around everything inside the body element and it’s been a long time since I applied CSS fixes for IE6, so to me personally the pros outweigh the cons. They may or may not for you.

Posted on April 11, 2013 in Browsers, CSS