You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用last-child/last-of-type选择器修改最后一个div样式失效问题

问题原因分析

你遇到的问题核心在于 :last-child 和 :last-of-type 选择器是相对于元素的直接父元素生效的,而不是针对所有拥有.blue-back类的元素集合。

看你的DOM结构:每个.blue-back都被包裹在独立的.col-md-4容器里,也就是说,每个.blue-back都是它父元素(.col-md-4下的div)的唯一子元素,所以这两个选择器会匹配所有的.blue-back元素(因为每个都是自己父级的最后一个子元素/同类型元素),这显然不是你想要的效果;如果你的代码里所有.blue-back都没变红,那大概率是选择器的作用范围理解错了。

解决方案

要选中最后一个.blue-back,你需要先定位到最后一个包含它的.col-md-4容器,再选中里面的.blue-back,这样就能精准定位到目标元素:

/* 选中.row下最后一个.col-md-4里的.blue-back */
.row .col-md-4:last-child .blue-back {
  background-color: red;
}

另外也可以用:nth-last-child(1)替代:last-child,效果完全一致:

.row .col-md-4:nth-last-child(1) .blue-back {
  background-color: red;
}
验证后的完整代码示例

给你整合后的可直接测试的完整代码:

<style>
.blue-back { 
  background-color: blue; 
  padding: 1rem; /* 加padding方便直观看到背景效果 */
}
/* 正确的目标选择器 */
.row .col-md-4:last-child .blue-back {
  background-color: red;
}
</style>
<div class="row">
  <div class="col-md-4">
    <div class="blue-back">
      <p class="mb-0 text-center text-white">Fase</p>
      <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
    </div>
  </div>
  <div class="col-md-4">
    <div class="blue-back">
      <p class="mb-0 text-center text-white">Fase</p>
      <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
    </div>
  </div>
  <div class="col-md-4">
    <div class="blue-back">
      <p class="mb-0 text-center text-white">Fase</p>
      <p style="font-size:29px; font-weight:600;" class="mb-0 text-center text-white font-weight-600">1</p>
    </div>
  </div>
</div>

这样最后一个.blue-back会变成红色,前两个保持蓝色,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Gago

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:23:45