:first-child pseudoclass and + combinator in IE7
- Published:
As of version 7, Internet Explorer (IE) supports :first-child CSS-selector and + combinator that allows to get HTML code much cleaner.
There is 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 next to the comment.
In the next 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 dynamically removed from DOM tree with JavaScript once HTML-page is loaded. 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;
}