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

如何用CSS分别定位不同分组中指定位置的class元素?

解决方案:定位指定分组内的目标元素

你可以通过组合使用:first-child/:nth-child()选择器精准定位目标元素,无需修改HTML结构,具体CSS代码如下:

/* 选中第一个.foo分组里的第3个.bar */
.foo:first-child .bar:nth-child(3) {
  color: red;
  font-weight: bold;
}

/* 选中第二个.foo分组里的第2个.bar */
.foo:nth-child(2) .bar:nth-child(2) {
  color: blue;
  font-weight: bold;
}

选择器说明:

  • .foo:first-child:匹配父容器下的第一个.foo元素
  • .bar:nth-child(3):在第一个.foo的子元素中,选中第3个(恰好是.bar)
  • .foo:nth-child(2):匹配父容器下的第二个.foo元素
  • .bar:nth-child(2):在第二个.foo的子元素中,选中第2个(恰好是.bar)

对应的HTML结构:

<div class="foo">
  <div class="bar">Non Target</div>
  <div class="bar">Non Target</div>
  <div class="bar">TARGET</div>
  <div class="bar">Non Target</div>
</div>
<div class="foo">
  <div class="bar">Non Target</div>
  <div class="bar">TARGET</div>
</div>

内容的提问来源于stack exchange,提问作者Matt The Greenside Gallery

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:44:51