Conditional comments are a feature of Microsoft Internet Explorer. They allow you to do some minimal browser detection (Internet Explorer versions or not Internet Explorer) and display HTML depending upon the rules you've set up. The beauty of these comments is that they are based on standard HTML comment tags. In fact, you can write an XHTML document, include these tags and it will still be valid XHTML code, unless you use invalid XHTML within the comment.
Here's what a conditional comment looks like:
<!--[if lte IE 7]>
<p>Welcome to Internet Explorer</p>
This comment will display the paragraph "Welcome to Internet Explorer" to Internet Explorer 7, 6, and 5 (IE 4 and lower do not support conditional comments). Other browsers, including IE 4 and lower, treat those lines as a standard comment and do not display anything.
How do you use conditional comments?
<!--[if (conditional) IE (version)]>
HTML within the comment to be displayed in IE
The conditional can be:
[if IE 8]
if you want it to exactly match the browser version
[if lt IE 8]
if you want a browser version less than the version number
[if lte IE 8]
if you want a browser version less than or equal to the version number
[if gt IE 7]
if you want a browser version greater than the version number
[if gte IE 7]
if you want a browser version greater than or equal to the version number
[if !IE 8]
if you want a browser version that is not equal to the version number
The version can be:
- the integer major version number
[if IE 8]
- a version vector with sub versions after the decimal point
[if IE 6.5]
Hiding HTML from IE
This trick is not valid XHTML.
You can also use conditional comments in a reverse fashion to hide HTML from Internet Explorer. The main difference is that you remove the -- from the comment tags:
This trick relies on the fact that other browsers don't recognize the tag "<![if> and so they ignore it and display the contents. While Internet Explorer treats this as a comment and comments out all the contents of this tag (if it meets the conditions).
Using Conditional Comments
Conditional comments are a great way to work with Internet Explorer, especially if you're using CSS. Internet Explorer has a lot of "gotchas" in its rendering of CSS, and so often you want to have a separate style sheet just for IE. Well, now you can create a second style sheet and display it only to Internet Explorer. If you place it second in your XHTML head, the cascade will insure that your IE styles will over-rule your non-IE styles.
<link href="styles.css" media="screen" type="text/css" />
<!--[if lte IE 6]>
<link href="ie6_styles.css" media="screen" type="text/css" />