当前位置: 动力学知识库 > 问答 > 编程问答 >

css - Weird behavior for :first-child and :nth-child

问题描述:

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;

}

see fiddle

Second example: (which does not hide the b-class for some reason)

body .b:nth-child(1) {

display: none;

}

see fiddle

Third example: (which finally hide the b-class for some reason)

body .b:nth-child(2) {

display: none;

}

see fiddle

Does anyone have a logical explanation of this behavior?

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: