Fix CSS Browser Compatibility using conditional comments

I’ve never had any incompatibly issues with different browsers whilst working on websites before – until today. For some reason IE7 decided it wanted totally misjudge my margins by about 30 pixels – totally distorting the site. Strange how it worked fine in any other browser (Including IE6 and IE8!). Anyway, conditional comments can be used to hack the CSS based on the browser being used. As this isn’t technically CSS, it’s HTML comments, it must be added in the headers tag on your HTML page. My fix was:

<!--[if IE]>
<style>
.item {
margin: 5px;
padding: 10px;
}
</style>
<--[EndIf]-->


Rules can be just for any IE version or can be version dependant from 5-8.

Another handy use is to load individual stylesheets, dependant on browser:

<link href="all_browsers.css" rel="stylesheet" type="text/css">
<!--[if IE]> <link href="ie_only.css" rel="stylesheet" type="text/css"> <![endif]-->
<!--[if lt IE 7]> <link href="ie_6_and_below.css" rel="stylesheet" type="text/css"> <![endif]-->
<!--[if !lt IE 7]><![IGNORE[--><![IGNORE[]]> <link href="ie7_plus.css" rel="stylesheet" type="text/css"> <!--<![endif]-->
<!--[if !IE]>--> <link href="not_ie.css" rel="stylesheet" type="text/css"> <!--<![endif]-->

You can leave a response, or trackback from your own site.

Leave a Reply