一个父元素可以有一个或多个子元素:
<div class="parent">
<div>Child</div>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
在这些孩子中,只有一个可以成为第一个。这是由:first-child匹配的:
<div class="parent">
<div>Child</div> <!-- :first-child -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
:first-child 和:first-of-type 之间的区别在于:first-of-type 将匹配其元素类型的第一个元素,在 HTML 中由其标记名称表示,即使该元素不是第一个子元素父母的。到目前为止,我们正在查看的子元素都是 divs,但请耐心等待,我稍后会讲到。
现在,反过来也成立:任何:first-child 也必然是:first-of-type。由于这里的第一个孩子也是第一个div,它会匹配both伪类,以及类型选择器div:
<div class="parent">
<div>Child</div> <!-- div:first-child, div:first-of-type -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
现在,如果您将第一个孩子的类型从div 更改为其他内容,例如h1,它仍然是第一个孩子,但显然不再是第一个div;相反,它成为第一个(也是唯一一个)h1。如果有任何其他div 元素跟随在同一个父元素中的第一个子元素之后,那么这些div 元素中的第一个元素将匹配div:first-of-type。在给定的示例中,在第一个孩子更改为 h1 后,第二个孩子成为第一个 div:
<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>
注意: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>
:last-child 和:last-of-type 也是如此:任何:last-child 必然也是:last-of-type,因为在其父元素中绝对没有其他元素跟随它。然而,因为最后一个 div 也是最后一个孩子,所以 h1 不能是最后一个孩子,尽管它是其类型中的最后一个。
:nth-child() 和:nth-of-type() 与任意整数参数一起使用时,在原理上非常相似(如上面提到的:nth-child(1) 示例),但它们的不同之处在于:nth-of-type() 匹配的潜在元素数量.这在What is the difference between p:nth-child(2) and p:nth-of-type(2)?中有详细介绍