Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 585
Chris Avatar asked Jan 29 '13 09:01

Chris


People also ask

Why is my last child not working?

:last-child will not work if the element is not the VERY LAST element. I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container.

Does nth child work with class?

The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings.

How does a nth child work?

Definition and Usage. The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do you target the nth child in SCSS?

You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() . For example, li:nth-child(3) will select the list item with an index value 3; that is, it will select the third list item.


1 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.

like image 105
BoltClock Avatar answered Oct 18 '22 14:10

BoltClock