css3中 nth-child 和 nth-of-type 的区别

参考:深入理解css3中 nth-child 和 nth-of-type 的区别 - peakleo - 博客园 

首先:nth-child 和 nth-of-type的索引都是从1开始的

nth-child 和 nth-of-type有什么不同?

直接上例子,看代码注释就好

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<style>

  /*ul下的第2个元素  且这个元素为li*/
  .ul li:nth-child(2) {
    color: red;
  }


  /*ul下的第2个li*/
  .ul li:nth-of-type(2) {
    color: green;
  }
</style>
<body>
<div>

  <ul class="ul">
    <div>zero</div>
    <li>one</li>    <!-- red -->
    <li>two</li>    <!--  green-->
  </ul>
</div>
</body>
</html>

如果在nth-child和 nth-of-type前不指定标签 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<style>
    
  /*ul下的第2个元素*/
  .ul :nth-child(2) {
    color: red;
  }


  /*ul下 的所有类型标签的第二个。*/
  .ul :nth-of-type(2) {
    color: green;
  }

  
</style>

<body>
<div>
  <ul class="ul">
    <div>first div</div>
    <li>first li</li><!-- 红色 -->
    <li>second li</li><!-- 绿色 -->
    <div>second div</div><!--绿色  -->
    <div style="padding-left:10px">
        <span>first span</span>
        <span>second span</span><!--绿色  -->
    </div>
  </ul>
</div>
</body>
</html>

 公式:或者说是算术表达式

使用公式 (an + b)。描述:表示周期的长度,n 是计数器(从 0 开始),b 是偏移值。在这里,我们指定了下标是 3 的倍数的所有 p 元素的背景色:

<style>
  p:nth-of-type(3n+0) {
    background: #ff0000;
  }
</style>
 

若是 :nth-of-type(4n+2) 就是选择下标是4的倍数加上2的所有元素

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值