css 中 :first-child 与 :first-of-type 有什么区别?

493 阅读1分钟

css 中 :first-child 与 :first-of-type 有什么区别?

我们来看一段代码:

<div>
    <p>我是第一个子元素</p>
    <span>我是第二个子元素</span>
    <h1>我是第三个子元素</h1>
    <p>我是第四个子元素</p>
    <span>我是第五个子元素</p>
    <h1>我是第六个子元素</p>
</div>
p:first-child  //匹配到的是“我是第一个子元素” p 元素,因为p元素是div的第一个子元素
span:first-child  //匹配不到任何元素, 因为在这里spandiv的第二个子元素,而不是第一个
h1:first-child  //匹配不到任何元素, 因为在这里h1div的第三个子元素,而不是第一个

在css3中定义了 :first-of-type 这个选择器,我们来看看有什么不同?

p:first-of-type  //匹配到的是“我是第一个子元素” p 元素,因为 pdiv 的所有类型为 p 的子元素中的第一个
span:first-of-type  //匹配到的是“我是第二个子元素”, 因为 spandiv 的所有类型为 span 的子元素中的第一个
h1:first-of-type  //匹配的是“我是第三个子元素”, 因为 h1div 的所有类型为h1的子元素中的第一个

因此,我们可以得出结论:

:first-child 匹配的是某个父元素的第一个子元素,可以说是结构上的第一个子元素

:first-of-type 匹配的是某个父元素下相同类型子元素中的第一个,这里不限制是结构上的第一个了,只要是该类型元素的第一个就行了

同样类型的选择器还有 :last-child 与 :last-of-type, :nth-child(n) 与:nth-of-type(n) 也可以这样去理解。

\