Drasty Speche

0 notes

IE 8 my CSS!

On a recent personal project I decided to experiment with some of the pseudo-classes available in CSS 3. I was immediately smitten, especially with :last-child. The new pseudo-classes aren’t supported in any version of Internet Explorer (before version 9, now in beta), so I decided to use JavaScript to add an ie-last-child class to the appropriate HTML elements. My CSS looked something like this:

nav li {
    float: left;
    margin-right: 1em;
}
nav li:last-child,
nav li.ie-last-child { margin-right: 0; }

This worked great in Internet Explorer versions 6 and 7—but IE 8 choked: the last <li> still had a right margin of one em. What happened?

It turns out that IE 8 ignores any style declarations associated with any pseudo-classes (or pseudo-elements) that it doesn’t recognize. The workaround is relatively simple. You need to declare the styles twice, like so:

nav li:last-child { margin-right: 0; }
/* a separate declaration, to allow IE 8 to recognize the style: */
nav li.ie-last-child { margin-right: 0; }

In my case, this double-declaration resulted in a mere 20 extra characters of code to maintain, which isn’t a big deal. With this style change, though, I was able to avoid the problem entirely, by relying on the :first-child pseudo-class, which is part of CSS 2.1 (and is relatively well-supported in IE 7 and 8):

nav li {
    display: inline; /* kill the IE 6 double-margin float bug */
    float: left;
    margin-left: 1em;
}
nav li.ie6-first-child, /* be kind to IE 6, via JavaScript */
nav li:first-child { margin-left: 0; }

It’s worth reiterating that this is an extremely simple example. If you have more complex styles that rely on CSS 3 pseudo-classes or pseudo-elements, consider yourself warned. The most advanced (released) version of Internet Explorer will force you to write almost twice as much code.

Filed under CSS IE8 bugs