IE Conditional CSS Comments

March 28, 2007 - 6:58 pm No Comments

I know this has blogged about many times over, but I recently came across this really handy CSS hack (yes, I think this qualifies as a hack) specifically for styling sites in IE.

Basically, only Internet Explorer (5 and onwards) on Windows can read these ‘comments’. Therefore, any CSS styles written within them are only interpreted and applied by IE. And better yet – you can write ‘if’ statements within these comments so that your CSS styles are only applied to particular versions of IE.

Pretty handy huh?

Here’s a quick example:



<!--[if gt IE 5]> table#content { width: 100%; !important; }
<![endif]-->

Here are the different ‘if’ operators:


<!--[if IE]> This comment applies to all versions of IE from 5 to 7.
<![endif]-->


<!--[if IE 6]> This comment applies to version 6 of IE.
<![endif]-->


<!--[if lt IE 6]> This comment applies to versions of IE less than version 6.
<![endif]-->


<!--[if lte IE 6]> This comment applies to versions of IE less than or equal to version 6.
<![endif]-->


<!--[if gt IE 6]> This comment applies to versions of IE greater than version 6.
<![endif]-->


<!--[if gte IE 6]> This comment applies to versions of IE greater than or equal to version 6.
<![endif]-->

There are a couple of gotchas you should be aware of before you use this great little hack.

  • Only IE on Windows will interpret these comments. Read: this hack will not work for IE on a Mac. If you need to style something for IE on a Mac, think about checking for the user agent using whatever script you’re programming in, if you’re using one at all, and including styles based on that instead.
  • Conditional statements just use the normal HTML comments and therefore can only be used in HTML pages. Read: this hack won’t work when written in a CSS file.

    I know the pain web designers and developers go through trying to get their sites to look the same in all browsers (trust me, I know!) so it might be quite tempting to use this hack all over your code. But keep in mind that this is just a hack and you should try to find more standards compliant ways of styling your sites using CSS that works well in all browsers (or at least that are important to you).

    • Share/Bookmark

Leave a Reply