不使用:last-child伪类,如何为最后一个子元素应用CSS样式?
问题与解决方案
问题背景
原本有父div包裹多个带someText类的div时,用以下CSS就能让最后一个someText里的p标签文字变蓝,其他为绿色:
.someText p{ color: green; } .someText:last-child p{ color: blue; }
现在移除了外层父div,多个someText div直接同级排列,需要实现同样的样式效果,同时想知道能不能不用:last-child伪类来实现。
可行方案
1. 用:last-of-type替代:last-child
如果这些someText元素都是<div>类型,且它们的父容器里没有其他同级div,:last-of-type可以精准选中最后一个someText元素:
.someText p { color: green; } .someText:last-of-type p { color: blue; }
它的作用是选择父元素下同类型(这里是div)的最后一个元素,只要结构符合就能生效。
2. 用:nth-last-child(1)伪类
这个伪类和:last-child功能完全等价,只是写法不同,也能选中最后一个同级的someText元素:
.someText p { color: green; } .someText:nth-last-child(1) p { color: blue; }
3. 不用“最后一个”类伪类的实现方法
如果完全不想用:last-child这类伪类,可以借助:not和:has选择器组合,选中后面没有同级someText元素的那个(也就是最后一个):
.someText p { color: green; } /* 选中后面没有.someText兄弟元素的目标 */ .someText:not(:has(+ .someText)) p { color: blue; }
注意::has选择器需要浏览器版本支持,现代主流浏览器(Chrome 105+、Firefox 121+等)都已支持。
内容的提问来源于stack exchange,提问作者user22335335
相关产品推荐
相关产品推荐

