How to…use conditional comments

August 5, 2006 | Published in: Browsers & Hacks | Tags: , , , , , 7

Conditional comments have been part of internet explorer since version 5, but a lot of programmers ignore them.

This article teaches the basics of using conditional comments, and shows some examples of their uses.


A conditional comment is a method of talking directly to a version of internet explorer above version 5, allowing you to pass
IE specific rules without affecting other browsers such as firefox.

By utilizing conditional comments you can effectively reduce the usage of css hacks to make your web pages compatible with
Internet explorer.

Common uses

With conditional comments you can:

  • Target IE specifically
  • Make IE 5+ ignore a block of code

A great usage, for example, would be using conditional comments with CSS style sheets so you can have certain IE specific css rules that you want other browsers to ignore.

The code

You may be aware that, in html, the syntax of a normal comment is:

1
<!--comment goes here-->

Comments can be placed anywhere in the document.

Now, a conditional comment looks like this:

1
<![if ]><![endif]>

Conditional comments can also be placed anywhere in your HTML document.

Types of conditional comment

downlevel-hidden

A downlevel-hidden comment is a comment that is visible only to the IE version you are targeting.

Example:

1
2
3
<!--[if IE]>
     <em>your code</em>
<![endif]-->

The above code will only be seen by IE versions 5 and up.

Other, older, versions of IE, and also other browsers, will not see the code enclosed by the tags, and will therefore ignore anything you put inside, hence the name, downlevel-hidden.

The other browsers just see the <– and –&rt parts, so it looks like a regular comment to them.

Just to show you, for reference, if you used the code,

1
2
3
<!--[if !IE]>
     <em>your code</em>
<![endif]-->

NO browser would see the code. This is because the rule is !IE, which means NOT IE. Therefore IE 5+ wont see the code, and since it is downlevel hidden, no other browsers will either.

Visibility conclusion:

Firefox/non-ie browsers – code hidden

Targeted IE – code visible

downlevel-revealed

A downlevel-revealed comment is a comment that is visible to the IE version you are targetting, and also non-IE browsers and old versions of IE. It is useful when you wish to make code invisible to a version of internet explorer, but you want non-IE browsers to still see it.

Example:

1
2
3
<![if !IE]>
     <em>your code</em>
<![endif]>

The above example would be visible to all browsers except IE versions 5+.

Validity

You may notice that the downlevel-revealed code provided by Microsoft does not validate correctly, the correct code is outlined on this page, or is shown below:

1
2
3
<!--[if !IE]>-->
     <em>your code</em>
<!--<![endif]-->

The difference between this downlevel-revealed code and the downlevel-hidden code is that the comment is closed after each line, so non-IE browsers will not ignore it.

Visibility conclusion:

Firefox/non-ie browsers – code visible

Targeted IE – code visible

Targeting specific IE versions and extra commands

The [if ] portion of the conditional comment code has extra functionality so you can target certain versions of IE, or exclude versions. These are outlined below.

Targeting an IE version

To target a specific version of IE you just add the version number in the if statement, for example, to target IE 6 only you could use:

1
2
3
<!--[if IE 6]>
     <em>your code</em>
<![endif]-->

You must leave a space between ‘IE’ and the version number.

Targeting multiple IE versions

If, for example, you wanted to target versions of IE older than IE 6, rather than writing individual statements for each version you could use the ‘less than’ comparison :

1
2
3
<!--[if lt IE 6]>
     <em>your code for versions less than IE 6, but not including IE 6</em>
<![endif]-->

If you wanted to target versions older than, and equal to IE6 you would use:

1
2
3
<!--[if lte IE 6]>
     <em>your code</em>
<![endif]-->

The commands for comparing versions are as follows:

lt – less than

lte – less than or equal too

gt – greater than

gte – greater than or equal too

Excluding an IE version/versions

To exclude a version you can make use of the ! (NOT) operator, for example, to target all IE versions except IE 6 you could use:

1
2
3
<!--[if !IE 6]>
     <em>your code</em>
<![endif]-->

This would mean if not ie 6.

You could also mix the not operator with multiple IE versions, for example to target all versions of IE except IE 6 and above you could use the code:

1
2
3
<!--[if gte !IE 6]>
     <em>your code</em>
<![endif]-->

This would mean if not greater than or equal to ie 6.

Version Vectors

Version vectors allow you to target minor versions of IE, for example you could target IE 5.5 instead of IE 5 as a whole. This is particularly useful, as some bugs are fixed in higher versions. The format of a version vector is x.xxxx, but you do not have to make the decimal 4 digits long, e.g 5.0 is valid, as is 5.0000, however the 5.0000 targets the 0000 build of the browser specifically.

Usage examples

Some of the best example of usage would be using conditional comments in conjunction with CSS. Say for instance you wanted to fix a box model error in IE 5, rather than use hacks you could just make a separate style sheet for IE 5 with modified width values of an element which wasn’t rendering correctly. You would then add the following to the header of the html page:

1
2
3
4
5
<!--[if IE 5]>
  <style type="text/css">
    @import url(ie5.css);
  </style>
<![endif]-->

And hey presto, IE 5 will use the fixed styling, no box model hacks needed. Of course with this method you would have to ensure the conditional comment was after the style sheet include, if not the style would be overwritten by the default style sheet. Of course another method that would not be affected by the order would be to just add the styling directly to the conditional comment :

1
2
3
4
5
<!--[if IE 5]>
  <style type="text/css">
    #element{width:200px;}
  </style>
<![endif]-->

Since styles in the document have a higher priority than those in the style sheets, it would take priority.

So there you have it, a simple guide to using conditional comments in your web pages to avoid hacks, I hope this was useful and don’t forget to post a comment. Thanks for reading!

Further reading

Microsofts conditional comments page

Found this post useful? Why not buy me a coffee!

Related Entries

7 Responses to “How to…use conditional comments”

RSS feed for comments on this post.

  1. Anthony says:

    Thanks for the article; I will be using for reference, the only thing you didnt mention is the downside to conditional comments and that is that if you wish to stop supporting a particular browser you would have to take the code out of all the HTML pages.

    Comment made on February 9, 2007 at 5:36 pm

  2. sophie says:

    Thanks for this. You have explained things in a very simple way that is easy to implement.

    Comment made on May 14, 2007 at 9:21 pm

  3. Joe Tapia says:

    Could you use a conditional comment to make a css image invisible in Firefox. Added css image is invisible in IE but shows up in FF. Purpose of added css to make the page retain formatting when printing. Or would this be more suited to a hack?

    Comment made on October 3, 2007 at 8:22 pm

  4. Jay Bee says:

    I know you have a newer article on conditional statements, and you use them here. Though if you’re using conditional statements, why would you ever use a hack for IE? Not that its bad or good (well, actually, hacks are bad imho), but once you start using the conditional, its probably a better idea to stay consistent. Not to mention the CSS is much nicer to deal with (and easier to troubleshoot) when you create separate stylesheets for each conditional. Just a thought. Good article.

    Comment made on October 11, 2007 at 4:09 pm

  5. AC says:

    How do you write the conditional comment for firefox???

    Comment made on April 14, 2008 at 10:05 pm

  6. Tetsuo says:

    @AC: Conditional comments are for targeting Microsoft browers only.

    Comment made on June 3, 2008 at 9:46 am

The comments are closed.

About this site

Blue Anvil is the online web design journal & portfolio of , a web designer from Norfolk, England. Read More »
ThemeSlice
  • Featured work - More

    • Beefjack
    • Integrity
    • theotaku.com
    • Manic Melon
  • Latest Tweet - More

    • For those planning on upgrading download monitor; backup first. The upgrade script should work in most cases but be sensible.
  • Out of the blue - More

    • Switched: From Shared to VPS

      It’s been about two weeks now since I made the transition from a shared reseller hosting account to a VPS (Virtual Private Server) account – impressions so far, excellent performance but fiddly to configure.

      The reason I wanted to change from shared hosting was the fact the server was always being hacked (even though ALL my scripts were secure), there was frequent downtime, support blamed me for problems every time, and it was slow as hell.

      Those used to a shared hosting environment would probably not know where to start when faced with configuring a VPS. Luckily, a lot of it was pre-configured when I received my account – certainly some of the major security holes were patched. I was not satisfied with those however. As a victim of hacking in the past (previous host swears it was not there fault, something I don’t believe) I took extra care to secure it as a much I could – configuring brute force detection, the firewall, installing mod security (excellent rules for that here: http://www.atomicorp.com/wiki/index.php/Atomic_ModSecurity_Rules) and going though multiple guides (like this one: http://www.webhostingtalk.com/showthread.php?t=468168) with a fine-tooth comb.

      The result? My pages are loading at least 6 times faster, I have had no down time (or at least have not noticed any), and I feel in control and happy. No longer am I at the mercy of shared hosts :)

      If your interested, I chose ServInt as my provider as they offered a great deal, as well as being a managed service (so I’m not on my own if I screw things up). I was tempted by the bells and whistles of Media Temple, but felt the ServInt service was better value.

    • Download Monitor 3.2.2 Maintenance Release

      Download Monitor has received some more love and has been updated. Here’s the change log from the new version:

      • Small bugfix in uploader.php – cat ID
      • Changed stats graph calculation – thanks lggemini
      • Changes to headers in download.php to avoid caching
      • File Browser fixes – $root was clashing with something….
      • exclude_cat works in all sections of download_page now
      • Removed hardcoding of /uploads/
      • Added action to download.php – should be able to use it to stop a download if you want – maybe limiting downloads per day or something? Whatever you want…
      • Made it so if you post new file on ‘edit’ screen, the post date is updated.
      • Fixed the ‘blank meta’ section which blanks out custom field values when nothing is set.
      • Moved ‘allow_url_fopen’ check.
      • Someone said downloads don’t work with spaces in the name. They do! Wasting my time sonny…
      • All work and no play make jolley a dull boy
      • Had to rename capabilities so they work. Apologies if you have to set this up again! Cheers to Mark Dingemanse.
      • {category_ID} custom format tag added. Useful if you want to send someone to its category on the DL page I guess. Also added {category_other} so when no category is set “other” is shown – this is because the download page can show an ‘other’ section if you want it to.
      • You can now manually edit the post date on the edit download screen.

      If you have edited capabilities for download monitor user permissions, you’ll have to again sorry! This is because I named them too long. Also, you should check your forced downloads still work because there was a logic error meaning they may not have been forced after-all…

      Enjoy.

    • Mahousive update to Download Monitor (3.2)

      Today I completed the update for the Wordpress Download Monitor Plugin – many tweaks, fixes, and features added. There were no changes to the database structure so people upgrading should be fine. Here is the list from the change log:

      • {user} tag added for custom formats
      • ‘autop’ option fix
      • Download page buttons applied with CSS so they are easier to customise/translate.
      • Fix for pagination bug after editing a download
      • Category output fix on edit downloads screen
      • Category urls on download page use ID rather than name to prevent errors when cats have the same names.
      • exclude_cat added to download_page shortcode
      • Localised ‘hits’ ‘date’ ‘title’ on download page
      • Option to disable the download logging
      • Read file ‘chunked’ some people found large files were corrupted so this should help (fingers crossed)
      • Added show_tags option to download page – displays x amount of tags on the download page.
      • File Browser root setting and download.php logic/mime types modified thanks to Jim Isaacs (jidd.jimisaacs.com)
      • Interface Improvements
      • Bulk edit categories, custom fields, tags, member only downloads
      • Added roles for download monitor admin – should be able to use with a role manager plugin if you want anyone other than admin to access the admin section e.g. http://wordpress.org/extend/plugins/capsman/
      • Change redirect after add
      • Edit Cat names/parents
      • Dedicated tags and thumbnails fields (they still use meta table though)

      And yes, those category link bugs are fixed at long last, and you can edit category names finally. Phew!

    • Wordpress Spam Stopper Plugin Updated

      Spam stopper has been updated to v3.1 – and most of it has been recoded. Here’s the full list of changes:

      • Added changelog to readme.
      • Email validation bug squashed
      • Cached comments now work; if user forgets to fill in antispam or makes a mistake (and the JS does not catch it) the users comment will not be lost.
      • Redone entire code to make it more efficient
      • Admin section added for changing the antispam question
      • Form ID and honeypot trap added to form
      • Fully localized

      You can get the plugin from wordpress.org: http://wordpress.org/extend/plugins/spam-stopper/

      For support, please keep my comments clean and post on either the wordpress forums or my forum.

      To help support spam-stopper you can make a donation (buy me a coffee, or several) or rate it on wordpress.org. Thanks!