Strange behavior for: first-child and: nth-child
Is it just me or :first-child
and :nth-child
does not work logically?
If it's just me, then please explain to me how it works.
Here are 3 use cases that I don't really understand:
My HTML is as follows:
<div class="footer">
<span class="a">a</span>
<div class="b">b</div>
</div>
First example: ( doesn't hide the class for whatever reason b
)
body .b:first-child {
display: none;
}
Second example: ( doesn't hide the class for whatever reason b
)
body .b:nth-child(1) {
display: none;
}
Third example: (which finally hides the class b
for whatever reason)
body .b:nth-child(2) {
display: none;
}
Does anyone have a logical explanation for this behavior?
source to share
first-child
and nth-child(1)
mean the first child node. span.a
- the first node. It doesn't matter if you are using a combinatorial selector. .b
is not the first child, so it is not selected.
In this case, you can use .b:first-of-type
, because div
and span
are different types, but if they were span
, it wouldn't work. Using an extra selector such as .b
will do little for 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 can use for .b:first-child
.
source to share