Published 2012-02-01 02:29 by Leif Halvard Silli

Excluding a stylesheet from old versions of Internet Explorer

<!--[if lte ie 7]><style type=exclude ><![endif]-->

This method makes use of two features — conditional comments and knowledge about how a HTML parser parses the style element.

For IE7 and below:

  1. parser finds an opening tag in the conditional comment
  2. but because it does not know the style sheet type — type=“exclude” — it ignores the entire style sheet.
  3. parser looks for </style> (and thus ignores the <style> after the conditional comment), and when it finds it, it closes the element. End of story.

For all other browsers:

  • parser jumps over the conditional comment — and hence it read the style element normally.

Advantages of this method:
  1. It is XHTML-compatible. By what I mean that it, in a HTML5-compatible browser, creates the same DOM in both XML-mode and in HTML-mode.
  2. It does not affect syntax coloring in your text editor. (By contrast, if you wrap the entire style element inside conditional comments, then syntax coloring will probably color its content as any other HTML comment.)
Other uses: JavaScript
<!--[if lte ie 7]><script type=exclude ><![endif]-->
<script>function n(){var i = "Hello World";document.write(i);}</script>
</head><body onload="n()">

There’s nothing to say — it works the same way as the CSS.