To target specific browsers with style

Published 2012-02-01 12:24 by Leif Halvard Silli

In untarget specific browsers with style, I showed how to — eh — untarget browser with this method. But the same method and principle can be used to target specific browsers too.

Targeting a stylesheet for Internet Explorer 7 only
<!--[if lte ie 7]><style>/*<![endif]-->
<style  type="text/html" >/**/
    p{color:red;}
</style>
Explanation:

For IE7 and below:

  1. parser finds an opening tag inside the conditional comment
  2. parsers sees that element starts with a comment, which lasts until after the conditionall comment and behind the, next and “real” <style> tag.
  3. end of story.

For all other browsers:

  • parser jumps over the conditional comment — and hence it read the style element normally.
  • however, because this style element has its type attribute set to "text/html", all other browsers will ignore its content — it interpreted to not be CSS.

Advantages of this method:

The advantages are the same as for its twin sister — untarget specific browsers with style:

  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

Like its twin sister, this method can be used for JavaScript as well:

<!--[if lte ie 7]><script>/*<![endif]-->
<script type="text/html">/**/ function n(){var i = "Hello World";document.write(i);}</script>
</head><body onload="n()">
Explanation

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


|