How to solve :first-child CSS bug in IE 7

Yesterday, IE 7, once again, pushed me to the brink of going postal. Refusing to give up, I finally managed to find the problem.

Background

I was creating a top menu for a web site I was working on, and it needed some special styling for each first item, i.e. the first LI, and other styling for all others. Since it’s a controlled environment, IE 6 doesn’t need to be supported (Yay!); hence I thought I’d be using some cool CSS to solve it, as opposed to riddling the HTML code with classes.

Let’s look at my (somewhat :-) ) simplified example:

HTML code

<ul>
    <!-- First item is special -->
    <li>
        <a href="/">Start page</a>
    </li>
    <li>
        <a href="/">News</a>
    </li>
    <li>
        <a href="/">Contact</a>
    </li>
</ul>

CSS code

li {
    background: red;
}
li:first-child {
    background: blue;
}

The problem

No matter how I tweaked and changed my code, the :first-child CSS pseudo selector would not work in IE 7. Naturally, Microsoft claims it does support it, and, while going mental, I was trying to figure out whether it was just another crappy implementation that doesn’t work at all, or if there was something weird with my code.

The solution!

After pulling my last beard hair from my face, it dawned upon me! The key was the HTML comment preceding the first LI item, incorrectly interpreted by IE to be the first child element of the UL. In my defense, the HTML comment wasn’t written by me and yes, it could be in another place… :-)

Still, it’s a horrendous bug, and therefore I wanted to warn you! Be very careful about where you put your HTML comments, because the possible results will mess with your mind.

Posted in CSS,Developing,Technology,Web browsers |

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>