Notes on Conditional Comments

07/05/2009

Conditional comments are conditional statements inserted into HTML that are interpreted by Internet Explorer (IE); they are most often used to differentiate CSS rules for the various IE versions (IE5 and later). The advantage to using conditional comments is that, as their name implies, they are wrapped in the HTML comment tag (<!-- -->) and so keep your code clean and valid. Conditional comments can be used to address all IE browsers as a group, or target only a specific version or versions, and they remain hidden from other browsers, which don’t support them. Most front-end developers, including me, find that the use of conditional comments is the best way to deliver targeted CSS to Internet Explorer to try to repair its many rendering bugs (or to feed IE an entirely different style sheet).

There are two types of conditional comments: so-called down-level hidden and down-level revealed.

down-level hidden:

<!--[if IE]>Show this to IE<![endif]-->

down-level revealed:

<![if !IE]>Show this to everybody but IE<![endif]>

Browsers that don’t support conditional comments will ignore those that are down-level hidden, interpreting the code as a standard HTML comment; but down-level revealed comments will reveal the HTML content to other browsers because the conditional statements are ignored as invalid HTML tags (more on that below).

Syntax

The condition, which is enclosed in brackets [ ], always begins with if. Next, we have an operator such as ! used above. The possible operators are:

!
NOT
lt
LESS THAN
lte
LESS THAN OR EQUAL TO
gt
GREATER THAN
gte
GREATER THAN OR EQUAL TO
&
AND
|
OR

What follows the operator is the feature to test for. Since conditional comments are exclusively a feature of Internet Explorer, IE is the only possible value. We can, however, add a version number in order to target a specific version or range of versions:

<!--[if lte IE 7]>Show this to IE versions 7 and below<![endif]-->

Fixing down-level revealed

Down-level revealed comments may work as they are, but as noted above they are invalid HTML. To standards-conscientious designers and developers like me this is unacceptable. Roger Johansson wrote about a solution in 2005. To summarize, it turns out that the solution is quite simple. Instead of using Microsoft’s suggested syntax of

<![if !IE]>Show this<![endif]>

use the equivalent but valid

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

All set.

Conclusion

I find that conditional comments are more elegant, reliable, and easier to use than scripted techniques for identifying browsers when it is necessary to create a separate style sheet for Internet Explorer. You can read more of the specifics in Microsoft’s documentation.

Tags:

Leave a Comment