nth-child(n)和nth-of-type(n)

前言

ul>li:nth-child(3)
找到li标签的父亲的第三个孩子,这个孩子也必须是li,选择器才能生效

ul>li:nth-of-type(3)
找到li标签同级的所有的li,并从中找到第三个li

注意:
:nth-child(3)和:nth-of-type(3)只适合简单的层级结构,不然会出问题。比如:ul>li tr>td

demo1 - 被误伤

css

    .fu {
      height: 100px;
      padding: 30px 100px;
    }
    .zi1, .zi2 {
      position: relative;
      float: left;
      width: 100px;
      height: 100px;
    }
    .fu div:nth-child(1) {
      background-color: pink;
    }
    .zi2 {
      background-color: #ccc;
    }
    .grandson1 {
      position: absolute;
      left: 210px;
    }

html

  <div class="fu">
    <div class="zi1">
      <div class="grandson1">grandson1</div>
    </div>
    <div class="zi2">
      <div class="grandson2">grandson2</div>
    </div>
  </div>

结果
在这里插入图片描述

demo1 - 正常

后代选择器 改成 父子选择器

css

    .fu {
      height: 100px;
      padding: 30px 100px;
    }
    .zi1, .zi2 {
      position: relative;
      float: left;
      width: 100px;
      height: 100px;
    }
    
    /* .fu div:nth-child(1) { */
    .fu>div:nth-child(1) {
      background-color: pink;
    }
    .zi2 {
      background-color: #ccc;
    }
    .grandson1 {
      position: absolute;
      left: 210px;
    }

html

  <div class="fu">
    <div class="zi1">
      <div class="grandson1">grandson1</div>
    </div>
    <div class="zi2">
      <div class="grandson2">grandson2</div>
    </div>
  </div>

结果
在这里插入图片描述

demo2 - 正常

css

    .fu {
      margin: 100px;
    }
    .fu>div:nth-child(4) {
      background: tan;
    }
    .fu>div:nth-of-type(3) {
      background: pink;
    }

html

  <div class="fu">
    <p>
      son1---p1
    </p>
    <p>son2---p2</p>
    <div>son3---div1</div>
    <div>son4---div2</div>
    <div>son5---div3</div>
  </div>

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

demo2 - 不正常

css

    .fu {
      margin: 100px;
    }
    .fu>div:nth-child(4) {
      background: tan;
    }
    .fu>div:nth-of-type(3) {
      background: pink;
    }

html

  <div class="fu">
    <p>
      son1---p1
      <p>grandson1---p1</p>
      <p>grandson2---p2</p>
      <div>grandson3---div1</div>
      <div>grandson4---div2</div>
      <div>grandson5---div3</div>
    </p>
    <p>son2---p2</p>
    <div>son3---div1</div>
    <div>son4---div2</div>
    <div>son5---div3</div>
  </div>

结果
在这里插入图片描述

总结

1 使用父子选择器
2 父子选择器中的父级使用类名,减少误伤的概率。
3 子级不要再有太多的子级了,不然就会出现demo2这种无法解释的情况

解释不了,就很烦

解释不了,就很烦!!!解释不了,就很烦!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值