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

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

在css3中有两个新的选择器可以选择父元素下对应的子元素,一个是:nth-child 另一个是:nth-of-type。 但是它们到底有什么区别呢?

其实区别很简单::nth-of-type为什么要叫:nth-of-type?因为它是以"type"来区分的。也就是说:ele:nth-of-type(n)是指父元素下第n个ele元素,
而ele:nth-child(n)是指父元素下第n个元素且这个元素为ele,若不是,则选择失败。

文字未免听起来比较晦涩,便于理解,这里附上一个小例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<style>
  .demo li:nth-child(2) {
    color: #ff0000;
  }

  .demo li:nth-of-type(2) {
    color: #00ff00;
  }
</style>
<body>
<div>
  <ul class="demo">
    <p>zero</p>
    <li>one</li>
    <li>two</li>
  </ul>
</div>
</body>
</html>

结果如下:
在这里插入图片描述

上面这个例子,.demo li:nth-child(2)选择的是

  • one
  • 节点,而.demo li:nth-of-type(2)则选择的是
  • two
  • 节点。

    但是如果在nth-child和 nth-of-type前不指定标签呢?
    上面这个例子,.demo li:nth-child(2)选择的是

  • one
  • 节点,而.demo li:nth-of-type(2)则选择的是
  • two
  • 节点。

    但是如果在nth-child和 nth-of-type前不指定标签呢?

    <style>
      .demo :nth-child(2) {
        color: #ff0000;
      }
    
      .demo :nth-of-type(2) {
        color: #00ff00;
      }
    </style>
    

    这样又会是什么结果呢,看下html结构:

    <ul class="demo">
      <p>first p</p>
      <li>first li</li>
      <li>second li</li>
      <p>second p</p>
    </ul>
    

    结果:
    在这里插入图片描述
    如上可见,在他们之前不指定标签类型,:nth-child(2) 选中依旧是第二个元素,无论它是什么标签。而 :nth-type-of(2) 选中了两个元素,分别是父级.demo中的第二个p标签和第二个li标签,由此可见,不指定标签类型时,:nth-type-of(2)会选中所有类型标签的第二个。

    转载于https://www.cnblogs.com/peakleo/p/6232384.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值