css伪类:last-child或:first-child不生效

目录

一、问题

二、原因及解决方法

三、总结


tiips:如嫌繁琐,直接移步总结即可!

一、问题

1.想使用伪类:last-child给 for循环出来的最后一个元素单独添加样式。但是发现无论怎么写都没有添加上去。

2.真是奇怪呀,明明写的没有问题呀,但是检查元素的时候确实看不到样式。

二、原因及解决方法

1.预期效果:最后一个元素 红色;最后一个元素绿色

    html如下,效果如下图2-1所示

<template>
    <div class="test-area">
      <div
        class="test-box"
        v-for="(firstItem, firstKey) of firstData"
        :key="firstKey"
      >
        {{ firstItem.label }}
      </div>
      <div class="other-area"></div>
    </div>
</template>
<script lang="scss" scoped>
  .test-area {
    color: #333;
    .test-box {
      &:last-child {
        color: green;
      }
      &:first-child {
        color: red;
      }
    }
  }
</script>
图 2-1

2.为什么 最后一个元素不是绿色呢? 为什么 :first-child可以,:last-child不生效呢

检查元素,发现第一个元素添加了 :frist-child伪类样式,最后一个元素却没有。如图2-2所示

图 2-2

3.删除        <div class="other-area"></div>   竟然好了

图 2-3

4.把   <div class="other-area"></div> 放在第一个test-box前面,:first-child竟然失效了!!!!!!

图 2-4

5.原因::first-child只在被选中的第一个元素前面没有其他元素才生效;

 :last-child只在被选中的最后一个元素后面没有其他元素时才生效

上面的代码中.test-box:last-child后面还有同级的元素 other-area,所以不生效

6.解决方法:在被循环的test-box外面添加一个父盒子如图2-5所示

代码如下:

<template>
    <div class="test-area">
      <div class="box-area">
        <div
          class="test-box"
          v-for="(firstItem, firstKey) of firstData"
          :key="firstKey"
        >
          {{ firstItem.label }}
        </div>
      </div>
      <div class="other-area"></div>
    </div></template>
<script lang="scss" scoped>
  .test-area {
    color: #333;
    .test-box {
      &:last-child {
        color: green;
      }
      &:first-child {
        color: red;
      }
    }
  }
</script>

三、总结

1. :first-child,:last-child生效的前提

:first-child只在被选中的第一个元素前面没有其他元素才生效;

 :last-child只在被选中的最后一个元素后面没有其他元素时才生效

/*

希望对你有帮助!

如有错误,欢迎指正,非常感谢!

*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值