Andrew Gatenby

Conditional CSS in IE

Today I needed to apply a CSS tweak due to a rendering hiccup when viewing a site with IE6. After a bit of Googling, I remembered something I’d seen that was a relatively simple hack to serve up extra CSS instructions to a particular version of Internet Explorer.

Conditional comments can be included within a document that the IE engine will pickup and process:

<!--[if lt IE 7]>
<style>@import url(css/ie6.css);</style>
<![endif]-->

Not only can this be used to include additional stylesheet instructions, but it can be applied within the of a page for IE specific content.

A bit of research told me that there are a number of conditions that can be applied:

  • [if IE 6] - if equal to version 6
  • [if lt IE 6] - if less than version 6
  • [if lte IE 6] - if less than or equal to version 6
  • [if gt IE 6] - if greater than version 6
  • [if gte IE 6] - if greater than or equal to version 6

Exact version numbers of IE can be used, such as 6.014 etc. but it might be easier to stick to whole numbers.

Bookmark or share this article:

  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • Reddit
  • StumbleUpon

Category: CSS

Tagged:

2 Responses

  1. ramya says:

    conditional for IE is fine but what is the conditional for FF ?

  2. @ramya: There’s no elegant way suitable for Firefox that I’ve seen - certainly that doesn’t involve non-standards compliant hacks. Probably the most straight forward way would be to use PHP to detect the browser, and then include an extra stylesheet in the document head:

    if(strstr($_SERVER['HTTP_USER_AGENT'], 'Gecko/')) {
    	echo '<link rel="stylesheet" href="/css/firefox.css" type="text/css" media="screen" />';
    }

    That will match all Gecko based browsers, so you’ll be sure that Firefox will be taken care of, as well as browsers like Flock and Seamonkey that use the same rendering engine.

    You could extend it to target specific versions of Firefox if your needs require:

    // check to include the Firefox 3 stylesheet
    if(strstr($_SERVER['HTTP_USER_AGENT'], 'Firefox/3.')) {
    	echo '<link rel="stylesheet" href="/css/firefox3.css" type="text/css" media="screen" />';
    } else if(strstr($_SERVER['HTTP_USER_AGENT'], 'Gecko/')) { // else, include general Gecko stylesheet as appropriate
    	echo '<link rel="stylesheet" href="/css/gecko.css" type="text/css" media="screen" />';
    }

    Hope this helps!

Leave a Reply