104 css css-selectors
我不能告诉之间的区别element:first-child和element:first-of-type
比如说,你有一个div
div:first-child
→所有<div>元素都是其父母的第一个孩子.
div:first-of-type
→所有<div>元素都是<div>其父元素的第一个元素.
这似乎完全相同,但它们的工作方式不同.
有人可以解释一下吗?
Bol*_*ock 178
父元素可以包含一个或多个子元素:
<div class="parent">
<div>Child</div>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
在这些孩子中,只有一个孩子可以成为第一个孩子.这匹配:first-child:
<div class="parent">
<div>Child</div> <!-- :first-child -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
:first-child和之间的区别:first-of-type是:first-of-type它将匹配其元素类型的第一个元素,即HTML中的标记名称,即使该元素不是父元素的第一个子元素.到目前为止,我们所看到的子元素都是divs,但是请耐心等待,我会稍微谈谈它.
现在,反过来也是正确的:任何:first-child也是:first-of-type必要的.由于这里的第一个孩子,也是第一次div,它将匹配两个伪类,以及类型选择div:
<div class="parent">
<div>Child</div> <!-- div:first-child, div:first-of-type -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在,如果你将第一个孩子的类型div改为其他东西,比如h1,它仍然是第一个孩子,但它将不再是第一个孩子div; 相反,它成为第一个(也是唯一的)h1.如果div同一父项中的第一个子项后面有任何其他元素,则这些div元素中的第一个将匹配div:first-of-type.在给定的示例中,第二个孩子成为第div一个孩子改为h1:
<div class="parent">
<h1>Child</h1> <!-- h1:first-child, h1:first-of-type -->
<div>Child</div> <!-- div:nth-child(2), div:first-of-type -->
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
注意:first-child相当于:nth-child(1).
这也意味着虽然任何元素一次只能匹配一个子元素:first-child,但它可以并且将拥有与:first-of-type伪类匹配的子类数与它具有的子类型数一样多.在我们的示例中,选择器.parent > :first-of-type(具有隐式*限定:first-of-type伪)将匹配两个元素,而不仅仅是一个:
<div class="parent">
<h1>Child</h1> <!-- .parent > :first-of-type -->
<div>Child</div> <!-- .parent > :first-of-type -->
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
同样适用于:last-child和:last-of-type:任何:last-child也是必要的:last-of-type,因为在其父级中绝对没有其他元素.然而,因为最后div一个孩子也是最后h1一个孩子,尽管是最后一个孩子,但它不能是最后一个孩子.
:nth-child()并:nth-of-type()用任意的整数参数中使用(如在时原则上起作用非常类似于:nth-child(1)上述的例子),但它们的不同是在通过匹配元素的潜在数量:nth-of-type().这在详细覆盖的是什么P之间的区别:第n个孩子(2)和p:第n-的式(2)?
Wen*_*Wen 14
我已经创建了一个示例来演示这里first-child和之间的区别first-of-type.
HTML
<div class="parent">
<p>Child</p>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.parent :first-child {
color: red;
}
.parent :first-of-type {
background: yellow;
}
.parent p:first-child {
text-decoration: line-through;
}
// Does not work
.parent div:first-child {
font-size: 20px;
}
// Use this instead
.parent div:first-of-type {
text-decoration: underline;
}
// This is second child regardless of its type
.parent div:nth-child(2) {
border: 1px black solid;
}
Run Code Online (Sandbox Code Playgroud)
要查看完整示例,请访问https://jsfiddle.net/bwLvyf3k/1/