The IE7 CSS Hack

Saturday, January 28, 2006 by Nicholas Gagne

The developers of Microsoft Internet Explorer 7 claimed to have removed all of the CSS hacks, I had a feeling that, based on Microsoft's reputation of having one of the poorest QA process, a CSS hack for IE7 must exist. I am aware that we could ues Internet Explorer's conditional comments to deliver a seperate stylesheet, but there are known problems with that method if someone has more than one version of IE installed, so for this article we will focus on a CSS hack.

I happened upon a Beta 2 Preview build of Internet Explorer 7, and set up a test page. Here is what my CSS looks like:

#item {
    width: 200px;
    height: 200px;
    background: red;
}

Here is the corresponding HTML:

<div id="item">some text here</div>

Now I begin by adding a lang attribute to my body element:

<body lang="en">

Now, add the CSS to target our div element and start filtering out browsers:

*:lang(en) #item{
    background:green !important;
}

I've used !important to override the background property previously set. The :lang selector is not supported by IE7 and therfore all versions of Internet Explorer will not read these styles. Unfortunately, Safari also does not support this attribute. We will need to add some more CSS to target Safari:

#item:empty {
    background: green !important
}

The :empty selector is part of the CSS3 specification, and although it is not accurately supported by Safari, it will still select the element (whether it is empty or not). Now, the green box will show up in every browser except all versions of Internet Explorer. With this IE7 CSS hack you will be able to apply specific styles that will only affect all versions of Internet Explorer including Internet Explorer 7. The IE7 CSS hack has been tested, and found to be working correctly, in the following browsers:

  • IE7 Beta 2 Preview/Win
  • IE5.01+/Win
  • Firefox 1.5/Win
  • Opera 8.5/Win & Linux
  • Netscape 7.01, 8/Win
  • Mozilla 1.7.12/Win & Linux
  • Safari 2/Mac
  • Firefox 1.0.4/Linux
  • Epiphany 1.4.8/Linux
  • Galeon 1.3.20/Linux
Screenshot of the IE7 css hack in IE7Screenshot of the IE7 css hack in Firefox 1.5

View the IE7 css hack test page to try it out in your browser. If you want to try it out in IE7 Beta 2, you may be able to Google for a download link, otherwise you can definitely find it on most P2P networks can get it directly from Microsoft. All of the CSS I have used in this example passes the W3C's CSS validator. Unfortunately, you won't be able to validate your HTML using XHTML 1.1 or later, since we are using the lang attribute which has been removed. If you can verify that this hack works or does not work correctly in any browser not listed here, please post a comment with your browser and operating system.