Matt's Blog

Conditional Comments

August 15th, 2007 at 2:41 PM (17 years ago) by Matt Freedman

Conditional comments are special HTML comments that can be used to do certain things in Internet Explorer only without using any scripting. They only work in Internet Explorer and were introduced starting with version 5. This can be quite useful when making a Website because all Browsers don’t display things exactly the same. Usually Opera, Safari and Firefox all display it alike, but Internet Explorer may display it differently (for me, usually correctly 😛 ). This is where you can use conditional comments to make IE use, say, some different CSS values than other Browsers.

Take Matt’s Blog’s current theme for example (the upcoming theme also does this). I use conditional comments to have a stylesheet called ie7style.css to be loaded if the Browser is Internet Explorer 7. In that stylesheet, it overrides values set in the main stylesheet to make the Sidebar display correctly in IE7. These conditional comments are only recognized in IE. Other browsers just see them as meaning-less HTML comments.

Conditional comments start are usually in the format of:

<!--[if <em>expression</em>]>Special IE Only HTML<![endif]-->

Usually (if not always) the expression contains “IE”. You can then add a version number after that (eg. “IE 7”). Here’s an example of what you would use if you wanted to show it to all versions (above 5) of IE:

<!--[if IE]>Will Show Up in Internet Explorer Only<![endif]-->

For IE 7 only:

<!--[if IE 7]>Will Show Up in Internet Explorer 7 Only<![endif]-->

You can only use operators such as less-than (lt), less-than or equal-to (lte), greater-than (gt) and greater-than or equal-to (gte). Here’s an example:

<!--[if gte IE 7]>Will Show Up in Internet Explorer 7 and Above Only<![endif]-->

Conditional comments are particularly useful for specifying IE only stylesheets that overwrite settings in the main stylesheet, to make your Site look good cross-browser.

You can see the full list of expressions in the Microsoft Developer Network.

Now, if only other Browsers would implement conditional comments…

Leave a Reply

Quote selected text

Leave the following field empty: