first-child 与 first-of-type

二者均是用于选择某父级元素的第一个子元素。区别如下:

<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。再来看看兼容性:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值