经验|css中:last-child不生效的解决方法

2024年04月06日 21:19:09益点益滴1098

在产品需求中,总有对第一个或者最后一个同类元素进行特殊的样式处理。

如果使用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不生效的解决方法的内容到这里就结束了,喜欢的话可以给我们点赞鼓励~

超赞,真给力!嗯,必须鼓励~

打赏 0
账号:mxy310@163.com[复制]
账号:77940140[复制]