奇怪的行为为:第一个孩子和第十八个孩子

问题描述:

它只是我,或者是:first-child:nth-child不符合逻辑的方式?奇怪的行为为:第一个孩子和第十八个孩子

如果只是我,请解释我是如何工作的。

下面是使用的3个例子,我真的不明白:

我的HTML如下:

<div class="footer"> 
    <span class="a">a</span> 
    <div class="b">b</div> 
</div> 

第一个例子:(隐藏b - 类由于某种原因

body .b:first-child { 
    display: none; 
} 

see fiddle

第二个例子:(隐藏b -class出于某种原因

body .b:nth-child(1) { 
    display: none; 
} 

see fiddle

第三个例子:(终于隐藏b - 班级出于某种原因

body .b:nth-child(2) { 
    display: none; 
} 

see fiddle

没有人有此行为的合乎逻辑的解释?

+1

第一个例子:“b”是父容器中的第一个孩子吗?不,因此它不是隐藏的。在这种情况下,你需要'.b:first-of-type'。第二和第三:b是第一个孩子吗?不,这是第二个。因此,结果。 – dfsq 2014-10-03 12:39:03

+0

谢谢@dfsq,我看到了[我可以使用](http://caniuse.com/)':nth-​​of-type',':nth-​​last-of-type()',':first-类型',':最后类型',':只有类型'。这似乎是我实际需要使用的那个。 – 2014-10-03 13:58:38

first-childnth-child(1)意味着第一节点。 span.a是第一个节点。使用组合选择器并不重要。 .b不是第一个孩子,所以没有被选中。

在这种情况下,你可以使用.b:first-of-type因为divspan是不同的类型,但如果他们都span s表示是行不通的。使用一个额外的选择像.b也不会有多大效果与第n个孩子选择除了在同类个案:

<div> 
    <div class=b>b</div> 
</div> 
<div> 
    <div>not b</div> 
</div> 
<div> 
    <div class=b>b</div> 
</div> 

那么你可能有一个使用了.b:first-child

+0

如果你设置了'b:first-child',只是为了确定第一个节点是否为'b',那么应用这个类。 – DaniP 2014-10-03 12:40:11

+0

谢谢@Explosion Pills。对于那些有这些问题的人,我在[我可以使用](http://caniuse.com/)上找到了以下选择器':nth-​​of-type',':nth-​​last-of-type()' ,':first-of-type',':last-of-type',':only-of-type'。 – 2014-10-03 14:00:36