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

如何编写CSS选择器按子元素数量奇偶选中对应末尾元素

解决方案

你可以直接使用以下CSS选择器实现需求:

.container > .item:nth-last-child(2n + 1):first-child ~ .item:last-child,
.container > .item:nth-last-child(2n):first-child ~ .item:nth-last-child(-n + 2) {
  /* 这里填写你需要应用的样式规则 */
}

逻辑说明

  • 选择器第一部分匹配奇数个子元素的场景:
    .item:nth-last-child(2n + 1):first-child 表示第一个子元素同时是倒数第奇数个,说明当前.container下的.item总数量为奇数,后续通过~ .item:last-child选中最后1个.item。
  • 选择器第二部分匹配偶数个子元素的场景:
    .item:nth-last-child(2n):first-child 表示第一个子元素同时是倒数第偶数个,说明当前.container下的.item总数量为偶数,后续通过~ .item:nth-last-child(-n + 2)选中最后2个.item。

效果验证

你可以搭配以下测试样式快速确认效果:

/* 基础样式 */
.container > .item {
  padding: 8px;
  border: 1px solid #eee;
  margin: 4px 0;
}
/* 目标选中样式 */
.container > .item:nth-last-child(2n + 1):first-child ~ .item:last-child,
.container > .item:nth-last-child(2n):first-child ~ .item:nth-last-child(-n + 2) {
  background-color: #e5f6ff;
  border-color: #25b3f5;
}
  • 3个.item时,只有最后一个内容为c的元素会被加上蓝色样式
  • 4个.item时,最后两个内容为c、d的元素都会被加上蓝色样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 01:57:02