Many of us would have come across scenarios where we wanted a different Stylesheet or CSS properties for IE (Internet Explorer). While many would have resorted to Feature detection / browser detection there is an easier approach to achieve this. You can use Conditional comments to target Internet Explorer or different versions of IE.

Conditional Comments are basically HTML comments with expressions in it which ONLY IE understands. Hence the other browsers ignore everything written within the Conditional comments as they treat it as a normal comment. This means that you can write something within these conditional comments that only IE would understand. Using this you can load a separate CSS just for the IE browser, or show a section of a page meant only for IE visitors or load a JavaScript just for IE etc.

Syntax of Conditional comments

A conditional comment mainly looks like a normal HTML comment but has an expression and sometimes a sub expression written within square brackets [ ] . For Example :

 

If the expression written within the square brackets return true, the statement within the comment block is parsed and rendered by IE. For example :

This statement on IE8 would return true and include the specified css file in the page. On the other versions of IE it would return false and hence the css file would not be included.

Operators in conditional comments

Below is the list of conditional comment operators you can use. It has been taken from microsoft’s official document on the topic.

 

ItemExampleComment
![if !IE]The NOT operator. This is placed immediately in front of the feature, operator, or subexpression to reverse the Boolean meaning of the expression.
lt[if lt IE 5.5]The less-than operator. Returns true if the first argument is less than the second argument.
lte[if lte IE 6]The less-than or equal operator. Returns true if the first argument is less than or equal to the second argument.
gt[if gt IE 5]The greater-than operator. Returns true if the first argument is greater than the second argument.
gte[if gte IE 7]The greater-than or equal operator. Returns true if the first argument is greater than or equal to the second argument.
( )[if !(IE 7)]Subexpression operators. Used in conjunction with Boolean operators to create more complex expressions.
&[if (gt IE 5)&(lt IE 7)]The AND operator. Returns true if all subexpressions evaluate to true
|[if (IE 6)|(IE 7)]The OR operator. Returns true if any of the subexpressions evaluates to true.

Examples of conditional comments

The following are few examples of Conditional comments in html.

 

While it is easy and convenient to use conditional comments please keep it in mind that conditional comments are NOT understood by IE10 + . So be careful if you are targeting all the versions of IE or while targeting IE10 specifically.

Hope you found this article interesting. Please feel free to comment.