nth-child does not work as expected

When I add divs together with the objects that I use nth-child on, it seems to get buggy.

I'll appreciate any help with this.

<html>
<style>
.documents > a:nth-child(2) {
    border:1px solid red;
}
</style>

<div class="documents">
    <!-- NO DIVS: WORKS FINE -->
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
</div>
<br />
<div class="documents">
    <div></div><!-- ONE DIV: STARTS WITH THE FIRST OBJECT -->
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
</div>
<br />
<div class="documents">
    <div></div><div></div><!-- TWO DIVS: DOES NOT WORK -->
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
</div>
</html>

http://jsfiddle.net/nwrhU/

Answers


This is not buggy behavior; there's simply been a common misunderstanding of how :nth-child() works.

When you add div elements to the beginning, the a that you're looking for no longer becomes the second child overall (which is what :nth-child(2) means). This is because when you add one div, that becomes the first child; in turn, the first a becomes the second child, and the second a becomes the third child. When you add a second div, that div becomes the second child and the a elements similarly get pushed forward another step, so a:nth-child(2) no longer matches anything.

If you're looking for the second a regardless of any other element types among its siblings, use a:nth-of-type(2) instead.


Need Your Help

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

c# visual-studio-2010 visual-studio-2012 xcopy

I'm not very familiar with post-build events, so I'm a little confused as to what's going wrong with my program. When compiling in visual studio 2010, I get the following:

Detecting active AVAudioSessions on iOS device

ios objective-c cocoa-touch avaudiosession

I'm trying to figure out if this is possible - my app activates an audio session that is initialized as: