解决css样式中last-child不生效的问题

需求

项目中需要使用v-for指令来渲染一个图片列表,

现状

发现,最后一个格子并没有跟下面绿色线对齐。

最后发现 是因为 每个格子都给了 margin-right:36px,影响到了最后一个格子

所以使用last-child 将最后一个格子的margin 属性去掉

首先我们得明白first-child和last-child是干什么用的:

复制代码
    first-child选择器用于选取属于其父元素的第一个子元素的指定选择器。
    last-child选择器用于选取属于其父元素的最后一个子元素的指定选择器。

我们需要注意,使用:first-child伪类时要保证前面没有兄弟元素节点,使用 :last-child 伪类时要保证后面没有兄弟元素节点。

未修改好的


html 复制代码
  <div v-for="(item, index) in exportData.slice(3, 8)" :key="index">
      <div class="murightPart devicePart rectImg defaultrectImg">
        <div class="deviceTitle">{{ item.name.slice(0, 2) }}</div>
           <div class="deviceTitle">{{ item.name.slice(2, 5) }}</div>
       </div>
     </div>
 </div>

项目中的CSS样式

css 复制代码
 .muPart {
    display: flex;
  }

  .murightPart {
    margin-right: 36px;
  }
    .murightPart :last-child{
    margin-right: 0px;
  }

修改后的代码

html 复制代码
   <div class="muPart">
            <div v-for="(item, index) in  exportData.slice(3, 8) "
             :key="index" 
             class="murightPart">
              <div class="devicePart rectImg greenRect">
                <div class="deviceTitle">{{ item.name.slice(0, 2) }}</div>
                <div class="deviceTitle">{{ item.name.slice(2, 5) }}</div>
              </div>
            </div>
          </div>

css 代码

css 复制代码
.muPart {
    display: flex;
  }

  .murightPart {
    margin-right: 36px;
  }
  .murightPart:last-child {
    margin-right: 0px;
  }

原因是,

从图上代码来看,
murightPart 样式类下设置了last-child,同时我们必须知道:last-child指的是父元素下的最后一个子元素 ,要实现last-child下的样式生效的话需要保证class为muPart 下的div标签没有兄弟标签,或者创建一个单独的div标签把需要last-child生效的标签包裹起来,同时first-child选择器也是同理。

从修改好的与未修改好的HTML做对比,修改好的HTML是class为muPart下的div标签就一个,靠着div里面的v-for来生成其他的元素,而未修改好的HTML下面除了包含着v-for的标签,还有一个其他的兄弟标签,渲染页面后把last-child下的元素给这个兄弟标签了,所有v-for下生成的最后一个标签的样式没有生效。

同时也可以考虑使用下first-of-type和last-of-type,

first-of-type 匹配的是该类型的第一个,类型是指什么呢,就是冒号前面匹配到的东西,比如 p:first-of-type,就是指所有p元素中的第一个。这里不再限制是第一个子元素了,只要是该类型元素的第一个就行了,当然这些元素的范围都是属于同一级的,也就是同辈的。

last-child 和 last-of-type 原理类似

相关推荐
cz追天之路6 小时前
华为机考--- 字符串最后一个单词的长度
javascript·css·华为·less
Light606 小时前
CSS逻辑革命:原生if()函数如何重塑我们的样式编写思维
前端·css·响应式设计·组件化开发·css if函数·声明式ui·现代css
前端Hardy12 小时前
祝大家 2026 年新年快乐,代码无 bug,需求一次过
javascript·css·html
be or not to be19 小时前
HTML+CSS 浮动与表格全总结笔记
css·笔记·html
秋雨雁南飞21 小时前
WaferMap.HTML
前端·css·html
舆通Geo优化21 小时前
2025年GEO优化选哪家好?长沙GEO优化公司排名:GEO服务商哪家靠谱?
javascript·css·html
GDAL21 小时前
Tailwind CSS 菜单实现全面讲解教程(基于书签篮网站场景)
前端·css·菜单
Reese_Cool21 小时前
一篇文章梳理 HTML + CSS 核心知识(含响应式与 Sass)
前端·css·html
OpenTiny社区21 小时前
博文精读:Chrome CSS 2025年回顾
前端·css·chrome·开源·opentiny
C_心欲无痕1 天前
css - 预处理器sass与后处理器postcss
css·sass·postcss