Codebox Software

HTML Conditional Comments

Published:

Note that conditional comments are no longer supported in recent versions of Internet Explorer (IE10 and above).

The HTML snippet below demonstrates a useful technique for separating Internet Explorer CSS rules from those intended for less 'special' browsers. This approach uses an IE-only feature called Conditional Comments, and works without any JavaScript or CSS Hacks:

<head>
    <![if !IE]>
        <link rel="stylesheet" type="text/css" href="nonIE.css" />
    <![endif]>
    <!--[if IE]>
       <link rel="stylesheet" type="text/css" href="IE.css" />
    <![endif]-->        
    <link rel="stylesheet" type="text/css" href="shared.css" />
</head>
<body>
    ...

Because of the way that Internet Explorer treats conditional comments, it will ignore the first <link> tag, but will process the second one; so IE sees the HTML like this:

<head>
    <link rel="stylesheet" type="text/css" href="IE.css" />
    <link rel="stylesheet" type="text/css" href="shared.css" />
</head>
<body>
    ...

Since conditional comments are an IE-only feature, other browsers treat them as ordinary HTML tags. The first pair of tags <![if !IE]> ... <![endif]> won't be recognised as valid HTML, and so will be ignored, but the <link> tag between them will be processed as normal. The second pair of tags <!--[if IE]> ... <![endif]--> form a valid HTML comment, and so the <link> tag in between them will be ignored. So, non-IE browsers see the page like this:

<head>
    <link rel="stylesheet" type="text/css" href="nonIE.css" />
    <link rel="stylesheet" type="text/css" href="shared.css" />
</head>
<body>
    ...

Conditional Comments can also distinguish between different versions of Internet Explorer, so you can have separate stylesheets for each version if you like. The full syntax is described here, notice the charming way in which the article uses the term 'downlevel browser' to refer to 'Any browser except for Internet Explorer 5 and later'.