在产品需求中,总有对第一个或者最后一个同类元素进行特殊的样式处理。
如果使用js来判断哪个是第一个、最后一个也并不是不可以。
但是,完全 的管理范围 呢?
css选择器出场!
下面仅展示 效果
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. 非期望效果
但有时候 实现的却和想象中的 不太一样!!!!
代码如下:
- <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>
复制代码
看代码也可以看出来,仅仅是 ,明明把 是设置给了 ,但是需要的效果却没有了。
3. 分析问题
为什么:last-child没有起作用?
3.1 el:last-child 的匹配规则
1.查找 el 选择器匹配元素的所有同级元素(siblings)
2.在同级元素中查找最后一个元素
3.检验最后一个元素是否与选择器 el 匹配
期望中的效果实现了,是因为 匹配到的最后一个元素也是 。
非期望效果出现,是因为 匹配到的最后一个元素也是 而不是 。
4. 解决办法
方法1、
让 在其父元素内没有其它的标签,即让其父元素仅包含该种类型标签
方法2、
使用其它标签选择器
具体使用规则 :last-of-type — MDN
到此这篇关于css中:last-child不生效的解决方法的文章就介绍到这了,更多相关css :last-child不生效内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章,希望大家以后多多支持晓枫资讯! 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |