codeRambler Ramblings on code, the web, and technology

How to target specific IE browsers using just HTML?
Wednesday April 18th 2007, 11:08 am
Filed under: Javascript, Web development

Many people were introduced to conditional comments with the introduction of IE7 and their grass-roots call to action to stop using “CSS Hacks” to target specific IE browser versions.

Conditional comments are totally valid markup (for HTML as well as XHTML doctypes) that cause IE browsers running in Windows (the old Mac versions of IE ignored them completely) to parse the contents of the commented markup.

The following code shows how a conditional comment can be used to match “all versions of IE less than version 7″ and include an extra css file and an extra div in the content of the page:

<html>
<head>
  <link href="default.css" type="text/css" rel="stylesheet" />
<!––[if lt IE 7]>
  <link href="iexplore.css" type="text/css" rel="stylesheet" />
<![endif]––>
</head>
<body>
  <h1>Testing</h1>
<!––[if lt IE 7]>
  <div>I'm an old IE running in Windows</div>
<![endif]––>
</body>
</html>

Because of the start HTML comment code (<!--), everything until the close HTML comment code (-->) is treated as a comment for non matching IE Windows browsers.

The code that is actually rendered by the browser is different when viewed in IE Windows browsers older than IE7 and any other browser:

<html>
<head>
  <link href="default.css" type="text/css" rel="stylesheet" />
  <link href="iexplore.css" type="text/css" rel="stylesheet" />
</head>
<body>
  <h1>Testing</h1>
  <div>I'm an old IE running in Windows</div>
</body>
</html></code>

This is the code that is rendered in other browsers:

<html>
<head>
  <link href="default.css" type="text/css" rel="stylesheet" />
</head>
<body>
  <h1>Testing</h1>
</body>
</html>

You might choose to use this to set some variables on the page for javascript to use – without having to worry about user agent detection issues and spoofing browsers (remember that this will not work for the old IE Mac browsers – only Windows):

<script type="text/javascript">
  var isIE=isIE5=isIE6=isIE7=false;
</script>
<!––[if IE>
  <script type="text/javascript">
    isIE=true;
  </script>
<![endif]––>
<!––[if IE 7>
  <script type="text/javascript">
    isIE7=true;
  </script>
<![endif]––>
<!––[if IE 6>
  <script type="text/javascript">
    isIE6=true;
  </script>
<![endif]––>
<!––[if IE 5>
  <script type="text/javascript">
    isIE5=true;
  </script>
<![endif]––>

Be sure to check out the difference between down-level hidden (which is what I have used all the examples in this FAQ) and down-level revealed at the MSDN conditional comments page.