A better way to have browser specific CSS

April 12, 2013 / Updated: April 25, 2015 / Lena Shore
Filed under:

codeIf you are developing websites you know that not everything works across all browsers. You also know you have to make special allowances for some browsers (*cough* IE *cough*).

Before you may have had special external style sheets that directed those special CSS rules for specific browsers.

Something like this:

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

Wouldn’t it be nice to be able to have all your CSS in one single style sheet to keep your speed up? If this appeals to you, you can add conditional styles based on the browser:

<!-- [if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!-- [if IE 7 ]>    <html class="ie7"> <![endif]-->
<!-- [if IE 8 ]>    <html class="ie8"> <![endif]-->
<!-- [if IE 9 ]>    <html class="ie9"> <![endif]-->
<!-- [if (gt IE 9)|!(IE)]><!--> <!--<![endif]-->

When you are using IE7 to test a website, it will now have the new class applied to the HTML tag. The other advantage is this doesn’t add extra tags to your body tag should you need to use them.

Now you can create your CSS in the same style sheet like this:

.header { color: #000;}
.ie6 .header { color: #fff; }

Credit for this idea goes to Paul Irish. There is a great discussion about the pros and cons of this technique on his webpage here.