Using IE conditional comments inside a stylesheet

Dexter Schneider picture Dexter Schneider · Jul 28, 2012 · Viewed 96.2k times · Source

I know that you can use an IE conditional comment inside HTML:

<!--[if IE]>
  <link href="ieOnlyStylesheet.css" />
<![endif]-->

But what if I want to target only IE in a stylesheet, setting up a css rule for a specific element inside the html. For example, you can use this Chrome/Safari hack inside the css file as css code...

@media screen and (-webkit-min-device-pixel-ratio:0) {
    .myClass{
        background: #fff;
        background:rgba(255,0,255,0.7);
    }
}

But using the IE hack inside the CSS stylesheet like this:

 <!--[if IE]>
      .myClass{
        background: #fff;
        background:rgba(255,0,255,0.7);
    }
 <![endif]-->

does not work. What do I use inside a stylesheet to target IE only?

Answer

Derek Hunziker picture Derek Hunziker · Jul 28, 2012

Conditional comments do not work within stylesheets. Instead, you can use conditional comments in your HTML to apply different CSS classes or IDs to elements that you can then target with CSS.

For instance:

<!--[if IE]>
  <div id="wrapper" class="ie">
<![endif]-->
<!--[if !IE]>
  <div id="wrapper">
<![endif]-->

Also, there are tools such as Modernizr that do feature detection in a very similar way (by adding classes to the <html> element). You can use it to progressively enhance your design/script for newer browsers while still supporting older browsers.