CSS in Website Design - Tips #2 - January 5th, 2007

Using Conditional Comments in Internet Explorer
If you are a a bit of a web developer and are reading this blog, you will no doubt be aware of Microsoft’s frankly woeful support for W3C’s CSS specification. Developers have for years had to accommodate for Internet Explorer by either limiting what they want to do with their layout, or implement obscure “hacks” that will apply a different set of CSS rules dependent on the browser being used.

Fortunately, Microsoft kind of realised this and all of their recent releases of Internet Explorer support what is known as “conditional commenting”, and is an ideal and fairly clean way of achieving one of these hacks. You can use this pseudo code to tell Internet Explorer to include extra mark-up which other browsers will ignore, due to the way the comments are structured.

For example, if you have a CSS file containing rules just meant for Internet Explorer browsers, you can include them safely in the head of your document in the following way:

<!–[if IE]>
<link rel=”stylesheet” type=”text/css” xhref=”ie_styles.css” />
<![endif]–>

This tells any Internet Explorer browser to include the CSS file, while all other browsers will ignore everything within the comments, due to them being seen as just that… Comments! You can also take this further and be more specific as to which versions of IE you want to process the extra mark-up:

<!–[if IE 6]> (included if the browser is Internet Explorer 6)
<!–[if gt IE 5]> (included in versions of Internet Explorer newer than 5)
<!–[if lte IE 6]> (included in versions of Internet Explorer older than and including 6)

There are oviously a couple more variations which you should be able to work out from the ones given. Hopefully you will end up writing clean, well-structured CSS that works in all browsers anyway, without ever needing to use any of the strange ways of hacking your CSS to pieces!

Rik Weber
Web Developer

 Next »