This post might seem a bit unnecessary now that Internet Explorer 9 is right around the corner. But on the other hand – people are STILL using IE6 and IE7 and will continue to do so for a long time. So this is a skill that is necessary to know about.
I am all against those CSS hacks that exists out there. You know how it is – sometimes Internet Explorer just won’t behave as the other browsers. CSS hacks aren’t pretty and can screw things up. But you’ve got a job to do and a client that is waiting, so what do you do?
Enter conditional comments! A fool-proof way to serve different CSS files to different versions of Internet Explorer!
Why use conditional comments?
CSS hacks can get the job done. But they often rely upon faulty browser behaviour and thus isn’t very future-safe. Who knows how future browsers will interpret them?
Conditional comments is nothing but regular comments but with a add-on. All other browsers reads it as comments and you can be 99% sure that future non-IE browsers will as well. Let me give you an example:
<!--[if IE]> <link href="css/IE.css" type="text/css" /> <![endif]-->
As I said: regular comments but with an add-on. All regular browsers will view it as a comment and move on. IE browsers will read the style sheet. Excellent!
But wait – there’s more! Say what you will about Internet Explorer but that browser IS improving. IE8 and IE9 in particular seems to behave more or less like the other browsers, making an IE-specific stylesheet for those versions unneeded. They might even break the layout! So what now?
Conditional comments are actually quite smart! They allow you to target specific versions of IE, like this:
<!--[if IE 6]> <link href="css/IE6.css" rel="stylesheet" type="text/css" /> <![endif]-->
You see how simple it is? Only IE6 will read that CSS file! You thought that was good? Take a look at this:
<!--[if lte IE 7]> <link href="css/IE7.css" rel="stylesheet" type="text/css" /> <![endif]-->
The above example actually target IE version 7 AND BELOW! You see? More modern browsers will never read that specific CSS file.
An added bonus this technique is that it validates. And since it won’t break in any other browser, and probably never will, it’s a fool-proof concept. Code away!
