我分不清 element:first-child
之间的区别和 element:first-of-type
例如,你有一个 div
div:first-child
→ 全部 <div>
元素是其父元素的第一个子元素。
div:first-of-type
→ 全部 <div>
第一个元素 <div>
其父项的元素。
这看起来完全一样,但它们的工作方式不同。
谁能解释一下?
最佳答案
一个父元素可以有一个或多个子元素:
<div class="parent">
<div>Child</div>
<div>Child</div>
<div>Child</div>
<div>Child</div>
</div>
在这些 child 中,只有一个可以是第一名。这与 :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 中由其标记名称表示,即使该元素不是父元素的第一个子元素。到目前为止,我们正在查看的子元素都是 div
,但请耐心等待,我稍后会谈到这一点。
现在,反之亦然:任何 :first-child
也必然是 :first-of-type
。由于这里的第一个 child 也是第一个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>
现在,如果您将第一个 child 的类型从 div
更改为其他类型,例如 h1
,它仍将是第一个 child ,但不再是显然是第一个 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
也是最后一个 child ,所以 h1
不可能是最后一个 child ,尽管它是其类型的最后一个。
: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)? 中有详细介绍。
关于css - :first-child and :first-of-type?有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052882/