如何编写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
相关产品推荐
相关产品推荐

