Categories:

Conditional comment examples

Let's see a few practical uses of IE's conditional comments to serve browser specific HTML then. One of the most common uses is to serve IE specific CSS in the HEAD section of your page to compensate for some erratic or proprietary IE behaviour:

<!--[if IE]>
<style type=""text/css">
div.mycontainer {
width: 300px;
filter:alpha(opacity=100);
}
</style>
<![endif]-->

You can obviously also serve entire blocks of HTML content to only IE. Lets say you wish to use IE's proprietary marquee tag (work with me here) on your page:

Example:

Source code:

<!--[if gte IE 5]>
<marquee scrollAmount=3 direction=up width=200 height=150 style="background-color:lightyellow; border:1px solid black">
<p><img src="http://javascriptkit.com/dot.gif"> Two wrongs don’t make a right. -Cheales<p><img src="http://javascriptkit.com/dot.gif"> A bird in the hand is worth two in the bush. -Heywood <p><img src="http://javascriptkit.com/dot.gif"> The opposite of love is indifference. -Erin<p><img src="http://javascriptkit.com/dot.gif"> All is well that ends well. -Shakespeare
</marquee>
<![endif]-->

Unless you're using IE 5+, you wouldn't even know that a marquee existed in the spot above. Browser degradability insurance doesn't get any simpler than that to implement.

Now, lets say you wish to position a DIV on the page statically (even if the page scrolls) using the CSS property "position:fixed." Since IE6 does not support this property, we'll use conditional comments to display the DIV only in browsers other than IE6 such as Firefox, while leaving the door open for IE7+. Note that at the same time we also left the door open for IE5.x browsers to see the below DIV, which if you want to prevent, you'd have to resort simply to screening out IE altogether (using: <!--[if ! IE]>):

<style style="text/css">
#staticcontent{
position:fixed;
left: 0;
top: 0;
}
</style>

<body>
<![if ! IE 6]>
<div id="staticcontent" style="width: 100%">
This content stays perfectly static on the screen. The entire DIV and its contents is only shown in non IE browsers such as Firefox, and IE7+, presumed to support "position: fixed".
</div>
<![endif]>
</body>

Don't you just love conditional comments?