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.
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 IE 8] do something <!--[endif] -->
Where the [if IE 8] is an expression
<!--[if !(IE 8)] do something <![endif] -->
Where the !(IE 8) is a sub-expression
If the expression written within the square brackets return true, the statement within the comment block is parsed and rendered by IE. For example :
<!-- [if IE8]
<link rel="stylesheet" type="text/css" href="IE8.css" />
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.
|!||[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.
According to the conditional comment this is IE <br />
<!--[if !IE]> -->
According to the conditional comment this is NOT IE <br />
<!—[if (IE 6)|(IE 7)]>
This is either IE 6 or IE 7
<!--[if IE 7]>
<link type=”text/css” rel=”stylesheet” href=”ie7.css” />
<!—[if lt IE 8]>
<p>Please upgrade to IE8 or higher version</p>
Hope you found this article interesting. Please feel free to comment.