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

如何用CSS仅当最后3个元素任一含selected类时选中它们?

问题

想要仅用CSS实现:当容器中最后3个元素里任意一个拥有selected类时,把这最后3个元素全部选中并设置样式(不是只选中带selected的那个)。已经用JavaScript实现了效果,但不知道怎么结合:has()和:nth-last-of-type()来写CSS规则。

解决方案

可以利用CSS的:has()选择器检测容器内最后3个元素中是否存在带selected类的元素,再给这三个元素统一设置样式。核心规则逻辑:

  • 用.container:has(.normal:nth-last-of-type(-n+3).selected)匹配包含最后3个元素中任意一个带selected类的容器
  • 在该容器下,选中最后3个.normal元素并应用样式

核心CSS代码:

/* 当最后3个元素里有任意一个带selected类时,给这三个元素设置样式 */
.container:has(.normal:nth-last-of-type(-n+3).selected) .normal:nth-last-of-type(-n+3) {
  background-color: #A00;
}
完整示例代码

HTML

<p>CSS Only</p>
<div class="container">
  <div id="d0" class="normal selected">0</div>
  <div id="d1" class="normal">1</div>
  <div id="d2" class="normal">2</div>
  <div id="d3" class="normal">3</div>
  <div id="d4" class="normal">4</div>
  <div id="d5" class="normal">5</div>
</div>
<p>example with Javascript</p>
<div class="container">
  <div id="j0" class="example selected">0</div>
  <div id="j1" class="example">1</div>
  <div id="j2" class="example">2</div>
  <div id="j3" class="example">3</div>
  <div id="j4" class="example">4</div>
  <div id="j5" class="example">5</div>
</div>

CSS

.container {text-align: center;}
.normal, .example {
  display: inline-block;
  width: 3rem;
  color: white;
  background-color: #004;
  text-align: center;
  border: 2px solid transparent;
}
.selected{
  background-color: #0A0;
  border: 2px solid #0A0;
}
.active{background-color: #A00;}

/* 核心CSS规则 */
.container:has(.normal:nth-last-of-type(-n+3).selected) .normal:nth-last-of-type(-n+3) {
  background-color: #A00;
}

JavaScript(用于演示切换selected状态)

let sel=0;
setTimeout(setSelected, 1000);

function setSelected() {
  document.getElementById("d"+sel).classList.remove("selected");
  document.getElementById("j"+sel).classList.remove("selected");

  if (++sel>5) sel = 0;
  document.getElementById("d"+sel).classList.add("selected");

  // JS实现的对照效果
  document.getElementById("j"+sel).classList.add("selected");
  if (sel>=3) {
    document.getElementById("j3").classList.add("active");
    document.getElementById("j4").classList.add("active");
    document.getElementById("j5").classList.add("active");
  }else{
    document.getElementById("j3").classList.remove("active");
    document.getElementById("j4").classList.remove("active");
    document.getElementById("j5").classList.remove("active");
  }
  setTimeout(setSelected, 1000);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:45:01