How to Add Stylesheets for IE Only

It is very challenging to write only one CSS file to target all the browsers, especially to target IE.

We can add the IE specific style sheets using conditional comments. So we have to add one global CSS file for all browsers, and one for IE only to override or add styles specific to IE.

Conditional comments work as follows:

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

Basic structure is the same as an HTML comment (). Therefore all other browsers will see them as normal comments and will ignore them entirely. But, Internet Explorer has been programmed to recognize the special syntax, resolves the if and parses the content of the conditional comment.

What if we want to include separate css files for different versions of IE, you can do this by checking browser version as follows:

<!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css">
<![endif]-->
<!--[if IE 6]>
   <link rel="stylesheet" type="text/css" href="ie6.css">
<![endif]-->
<!--[if IE 5.5]>
   <link rel="stylesheet" type="text/css" href="ie7.css">
<![endif]-->

To target less or greater than to a specific IE version:

<!--[if IE lt 6]>
   <link rel="stylesheet" type="text/css" href="ie6-down.css">
<![endif]-->
<!--[if IE gt 6]>
   <link rel="stylesheet" type="text/css" href="ie6-up.css">
<![endif]-->

We can also write IE specific styles without using conditional comments as follows:

  /* for all browsers */
  div.test { 
     margin:5px;
  }
  /* IE specific style */
  *html div.test {
      margin:0px;
  }
  or
  div.test {
     margin:5px; /* for all browsers */
     *margin:0px; /* for IE only */
  }

Just add the “*html” before any css class or add “*” before any style to apply only for IE. But, this is kind of a hack, So I would recommend to use conditional comments approach.

One Comment

Leave a Reply to Laci Cancel reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner