二者均是用于选择某父级元素的第一个子元素。区别如下:
<div class="parent">
<div>Child</div> <!-- div:first-child, div:first-of-type -->
<div>Child</div>
<div>Child</div>
<div>Child</div>
</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>
以上,注意第二个例子中子元素的第一个div
可以使用div:first-of-type
选择,但却不可以使用first-child
看起来first-of-type
有更精确的粒度,也的确如此,所以应尽可能的使用。某些场景下,比如react使用emotion作为css in js
的方式,如果使用first-child
可能带来问题(在服务端渲染场景下,emotion会给父元素加入一个style节点,导致样式出现问题,这一点未验证,但react项目的console控制台报出了警告。)
index.js:1 The pseudo class ":first-child" is potentially unsafe when doing server-side rendering. Try changing it to ":first-of-type"
他也推荐你使用first-of-type
。再来看看兼容性: