Reputation: 664
Is it just me, or is :first-child
and :nth-child
not working a logical way?
In case that it's just me, then please explain me how it works.
Here is 3 examples of the usage which I really don't understand:
My HTML is the following:
<div class="footer">
<span class="a">a</span>
<div class="b">b</div>
</div>
First example: (which does not hide the b
-class for some reason)
body .b:first-child {
display: none;
}
Second example: (which does not hide the b
-class for some reason)
body .b:nth-child(1) {
display: none;
}
Third example: (which finally hide the b
-class for some reason)
body .b:nth-child(2) {
display: none;
}
Does anyone have a logical explanation of this behavior?
Upvotes: 3
Views: 182
Reputation: 191729
first-child
and nth-child(1)
mean the first child node. The span.a
is the first node. It doesn't matter that you use a combinatorial selector. .b
is not a first child, so it is not selected.
In this case you could use .b:first-of-type
because div
and span
are different types, but if they were both span
s that wouldn't work. Using an additional selector like .b
won't help much with nth-child selectors except in cases like:
<div>
<div class=b>b</div>
</div>
<div>
<div>not b</div>
</div>
<div>
<div class=b>b</div>
</div>
Then you may have a use for .b:first-child
.
Upvotes: 4