nth-of-type和nth-child的正确使用方式,last-child为什么不生效?

一、 首先注意一点: nth-of-type(n)和nth-child(n)  这里的n都是1开始的,不是0

二、讲一下 nth-of-type和nth-child 查找方式

1. select:th-of-type(n) 

根据select选择器找到一个dom元素(假设叫el1) ====>在同级兄弟节点找type和el1的type相同节点(这里type指dom的类型,如div、p、span等)====> 找到第n个元素  ====> 判断这个元素是否满足select选择器,如果满足样式生效,不满足不生效

2. select:th-child(n)

根据select选择器找到一个dom元素(假设叫el1) ====>找到同级兄弟节点====> 找到第n个元素  ====> 判断这个元素是否满足select选择器,如果满足样式生效,不满足不生效

三、nth-of-type和nth-child的区别

他们的区别就是上面标红部分,重点体现在type  和  child,一个要求type相同,一个只要是同级的child就可以

四、举栗子 —— last-child为什么不生效?

   <div class="parent">
      <div class="child">1</div>
      <div class="child">2</div>
      <div class="child">3</div>
      <div class="child">4</div>
      <div class="child">5</div>
      <div class="child">6</div>
      <div class="child">7</div>
      <div class="child">8</div>
      <div>我是type的干扰</div>
      <p>我是child的干扰,我不会干扰type</p>
    </div>

<style lang="scss" scoped>
  .child{
    height: 50px;
    margin-bottom: 10px;
    background-color: blue;
  }
  .child:last-of-type{
    background-color: red;
  }
</style>

.child:last-of-type 没有生效,因为最后一个元素是 <div>我是type的干扰</div> ,他没有.child 的class

.child:last-of-child没有生效,因为最后一个元素是 <p> ,他没有.child 的class

五、常用的表达方式

1.  :nth-of-type(n)  第n个;    对应的:nth-child(n)

2.  :last-of-type、:first-of-type  最后一个、第一个; 对应的:last-child、:first-child

3. :nth-of-type(odd)  第奇数个  even-偶数; 对应的 :nth-child(odd)

4. :nth-last-of-type(n)  倒数第n个; 对应的 :nth-last-child(n)

5. :nth-of-type(An + B)  n从0开始,A与B都是固定的整数,可以是负数,但计算结果小于1的都会被忽略, 同样适用 :nth-child

:nth-of-type(2n)   匹配 2、4、6  其实相当于 even

:nth-of-type(2n + 1)   匹配 1、3、5  其实相当于 odd

:nth-of-type(3n + 2)   匹配 2、5、8    从2开始间隔3

:nth-of-type(-n + 5)   匹配前5个

6. 与 :not() 联合使用

.child:not(:last-of-type)    除最后一个元素以外的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值