Writing IE-only CSS in a stylesheet for all browsers

IE in the Trash

Update (2009-03-26): I now recommend using conditional comments rather than cluttering your stylesheet with these hacks.  Check out my newer article “Preventing IE6 bugs” for more details.

Since IE was not originally developed according to standards, it has been a losing battle for Microsoft to bring it up to code. These discrepancies are a constant annoyance for web developers who must tweak their web sites to display correctly in IE even if they develop according to standards. Fortunately, some of these discrepancies can help develop elegant code that only executes in IE.

There are many reasons why someone would want certain CSS statements to affect only IE. A typical scenario: the bottom padding of a div is appearing larger in IE than it is in Firefox.

#searchbox {
padding-bottom: 4px;
}

<div id="searchbox">...</div>

Now lets say that the only solution is to change the CSS in IE so that there is no bottom padding. We can take advantage of IE’s failure to support the CSS specification’s !important statement. All of the newest versions of other web browsers support this statement.

#searchbox {
padding-bottom: 4px !important;
padding-bottom: 0px;
}

<div id="searchbox">...</div>

In browsers supporting the !important statement, the above code effectively tells the browser that the bottom padding of the searchbox element can not be overridden. Therefore, the next statement that sets the bottom padding to zero has no effect. However, since IE ignores the !important statement, the statement that sets the bottom padding to zero executes.

Recently, I found a wonderful article called “Ten CSS tricks you may not know” from evolt.org. Definitely worth a quick read.