nth-child does not work as expected

2019-04-06 11:08发布

问题:

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/

回答1:

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.