How to Detect IE with Conditional Comments

| April 26, 2008 at 6:27 am
How to Detect IE with Conditional Comments

One of the most frustrating things about web design is cross-browser compatibility. I research CSS tricks online and I see these blocks of script filled with * / \ in order to “hack” certain browser bugs. That stuff looks so ugly inside a stylesheet. Plus, exploiting a bug isn’t future-proof or good practice; the bugs could be fixed at any time, leaving the site design broken.

Internet Explorer is the biggest offender when it comes to not following web standards. Most of the CSS hacks are for IE. But Microsoft has actually provided a rather eloquent way of slipping in IE-only code.

Conditional comments will not only detect IE, they’ll also detect which version of IE the user is browsing with. Since different versions of IE have different problems, this is extremely useful. Here is an example:

<!--[if IE]>
Some IE. specific code goes here
<![endif]-->

<!--[if IE 7]>
Some IE 7 specific code goes here
<![endif]-->

The designer can write a separate stylesheet for IE or write specific stylesheets for each version of IE.

Conditional comments are only understood by IE. Other browsers will interpret them as normal comments and not execute any of the code inside.

I am very fond of this technique. It’s been around for a good while now, so I don’t know why I don’t see more CSS gurus implementing it. There’s no messy javascript that can freeze the page, eat up memory, and crash the browser (not to mention many people have javascript turned off). There are no CSS hacks that dirty up the stylesheet. It’s not perfect—it’d be nice if IE actually became standards compliant one of these days—but it’s better than the alternatives.

For more information, see the MSDN Library Entry: About Conditional Comments

Related Posts

Comments

No Comments

No comments yet.

Leave a Comment

(required)

(required)

Line and paragraph breaks are implemented automatically. Your email address is never displayed.

HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>