(not only) Internet Explorer conditional comments

Internet Explorer conditional comments are probably the best way to hack IE bugs. The way simple and easy in use.Syntax is following :

<!--[if expression]> 

Thanks to mere HTML comments code is hidden from all browsers, except Internet Explorer, which parses it if expression returns true. Expression is pretty flexible. You can detect Internet Explorer in general ([if IE]) as well as its particular versions ([if IE 7]). You can even use comparision ([if lte IE 7]) and logical ([if !(IE 6)], [if (IE 6)|(IE gte 8)]) operators. You can find some examples at the bottom.

You should by no means bother about Internet Explorer 5.x and lower as its usage is hardly noticeable. Probably just some dinosaurs somewhere and victims of fossilized corporate rules (feel sorry for you, really).

Simple like that.

But, what if you want to hide code from Internet Explorer and to display it in other browsers?

At first glance you might say it's impossible using syntax above. We can't order other browsers to parse and display code inside HTML comments, can we? Right, we can't, but what we can do is to trick all browsers using following syntax:

<!--[if !IE]> -->
<!-- <![endif]-->

It may look a little messy (actually if you ever had to use or write any dirty IE hacks, it should not), but it works. Table below illustrates what browsers parsers see and do:

Code Internet Explorer parser Other browsers parsers
<!--[if !IE]> IE conditional comment opening tag
(expression says not to parse the code in HTML comment)
HTML comment opening tag
--> ignores it HTML comment closing tag
HTML ignores it parses HTML code and displays it
<!-- ignores it HTML comment opening tag
<![endif]--> IE conditional comment closing tag HTML comment closing tag

So it's exactly what we wanted, Internet Explorer ignores the code and other browsers parses it. Pretty nice, isn't it?

In closing, here are some ready-to-copy-and-use examples of conditional statements with short explanation:

* - it's just joke of course. I saw it on some blog, don't remember author right now, sorry.

  1. by sobstel • July 2008