[前端] css中:last-child不生效的解决方法

2507 0
Honkers 2022-10-19 17:50:07 | 显示全部楼层 |阅读模式
在产品需求中,总有对第一个或者最后一个同类元素进行特殊的样式处理。
如果使用js来判断哪个是第一个、最后一个也并不是不可以。
但是,完全属于css的管理范围为什么要去使用js呢?
css选择器出场!
下面仅展示:last-child效果
1.期望效果

代码展示:

<template>
  <div class="root-container">
    <div class="father">
      <div class="child" v-for="item in 10" :key="item">
        一共10个元素,我是第{{item}}个
        <template v-if="item== 10">(css控制我的颜色)</template>
      </div>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.father {
  width: 500px;
  border: 1px solid #b2b6b6;
  text-align: center;
  .child {
    padding: 10px 0;
    &:last-child {
      color: red;
    }
  }
}
</style>
展示的效果也和期望中的一样,最后一个元素文字为红色


2. 非期望效果

但有时候:last-child实现的却和想象中的 不太一样!!!!
代码如下:

<template>
  <div class="root-container">
    <div class="father">
      <div class="child" v-for="item in 10" :key="item">
        一共10个元素,我是第{{item}}个
        <template v-if="item== 10">(css控制我的颜色)</template>
      </div>
      <p>我是多余的元素</p>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.father {
  width: 500px;
  border: 1px solid #b2b6b6;
  text-align: center;
  .child {
    padding: 10px 0;
    &:last-child {
      color: red;
    }
  }
}
</style>
看代码也可以看出来,仅仅是多了一个p标签,明明把:last-child是设置给了.child,但是需要的效果却没有了。


3. 分析问题

为什么:last-child没有起作用?
3.1 el:last-child 的匹配规则
1.查找 el 选择器匹配元素的所有同级元素(siblings)
2.在同级元素中查找最后一个元素
3.检验最后一个元素是否与选择器 el 匹配
期望中的效果实现了,是因为el:last-child匹配到的最后一个元素也是.child。
非期望效果出现,是因为el:last-child匹配到的最后一个元素也是p标签而不是.child。
4. 解决办法

方法1、
让:last-child在其父元素内没有其它的标签,即让其父元素仅包含该种类型标签
方法2、
使用其它标签选择器:last-of-type
具体使用规则 :last-of-type — MDN


到此这篇关于css中:last-child不生效的解决方法的文章就介绍到这了,更多相关css :last-child不生效内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章,希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

特级红客

关注
  • 3159
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行