:nth-child()和:nth-of-type()的区别

:nth-child()和:nth-of-type()的区别:

:nth-child()和:nth-of-type()都是css3的伪类选择器
先上代码

<div class="nthDiv">
  <div>div</div>
  <p>p1</p>
  <p>p2</p>
</div>
<style>
.nthDiv p:nth-child(2){
  background: yellow;
}
.nthDiv p:nth-of-type(2){
  background: #6cf;
}
</style>

效果图:
效果图

可以看到伪类选择器 :nth-child(2):nth-of-type(2) 括号中都是2,但指向的却是不同的元素。

是因为 .nthDiv p:nth-child(2) 选中的是.nthDiv子元素中的第二个,并且这个元素是p标签才会生效,而 .nthDiv p:nth-of-type(2) 选中的是.nthDiv子元素中的第二个p标签。

拓展:

可以运用数学表达式 2n2n+1 批量选择处于单双位置的子元素(可以用于选择表格的单双行之类的)
示例:

<div class="nthDiv">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
<style>
.nthDiv p:nth-of-type(2n + 1){
  background: yellow;
}
.nthDiv p:nth-of-type(2n){
  background: #6cf;
}
</style>

效果图:
效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值