Skip to content ↓


:first-child pseudoclass and sibling combinator in IE7

As of version 7, Internet Explorer (IE) supports :first-child CSS-selector and sibling combinator (+) allowing to make HTML code much cleaner.

There is a limitation though: if HTML code has a comment in place where browser expects to see an element according to CSS selector, IE7 will be “confused” and will not apply styles to actual element located next to the comment.

In the following example, styles will be applied to paragraphs in all popular browsers (including IE8), but not in IE7:

HTML:
<div>
    <!-- Comment before first element -->
    <p>First paragraph.</p>
    <!-- Comment between elements -->
    <p>Second paragraph.</p>
</div>
CSS:
P:first-child {color: #0f0; } /* first child paragraph */
P + P {color: #00f; } /* paragraph after another paragraph */

Fortunately, there is a workaround for this issue: HTML comments as DOM nodes can be removed from DOM tree dynamically with JavaScript once HTML page is loaded. This can be done, for example, with following function (see live example):

function removeComments() {
    // http://tanalin.com/en/blog/2011/08/ie7-css-first-child-adjacent/
    var elems = document.getElementsByTagName('*'),
        count = elems.length,
        comments = [];

    for (var i = 0; i < count; i++) {
        var elem = elems[i],
            childNodes = elem.childNodes,
            childCount = childNodes.length;

        for (var j = 0; j < childCount; j++) {
            var node = childNodes[j];

            if (8 === node.nodeType) {
                comments.push(node);
            }
        }
    }

    var commentsCount = comments.length;

    for (var k = 0; k < commentsCount; k++) {
        comments[k].removeNode();
    }

    // Forcing reflow (rerendering) to ensure styles are applied
    document.body.className = document.body.className;
}