在产品需求中,总有对第一个或者最后一个同类元素进行特殊的样式处理。
如果使用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`在处理元素样式时可能遇到的问题,通过实例展示了当`:last-child`应用于含有额外元素的情况时,无法达到预期效果。文章分析了`:last-child`的工作原理,并提供了两种解决方案:保持父元素内仅有目标类型的子元素,或者使用`:last-of-type`选择器。最后,强调了CSS选择器在避免不必要的JavaScript介入上的优势。
873

被折叠的 条评论
为什么被折叠?



