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>
This is not buggy behavior; there’s simply been a common misunderstanding of how
:nth-child()works.When you add
divelements to the beginning, theathat you’re looking for no longer becomes the second child overall (which is what:nth-child(2)means). This is because when you add onediv, that becomes the first child; in turn, the firstabecomes the second child, and the secondabecomes the third child. When you add a seconddiv, thatdivbecomes the second child and theaelements similarly get pushed forward another step, soa:nth-child(2)no longer matches anything.If you’re looking for the second
aregardless of any other element types among its siblings, usea:nth-of-type(2)instead.