如何用CSS选择主元素的最后子元素而非子级元素的最后子元素
如何仅选中容器的直接最后一个带指定类的子元素?
你遇到的问题是因为last-child和last-of-type会匹配所有层级父元素下符合条件的元素,而非仅限定在.container的直接子元素中,所以嵌套里的sub-two也会被选中。
正确的解决方案
使用**子选择器>**限定选择范围为.container的直接子元素,再结合类选择器和:last-child,就能精准选中目标元素:
/* 选中.container的直接子元素中,既是最后一个子元素又带有.some-class的元素 */ .container > .some-class:last-child { background: lightblue; }
如果可以确定.container的最后一个直接子元素必然带有.some-class,也可以简化为:
.container > :last-child { background: lightblue; }
代码示例
<div class="container"> <div class="some-class">one</div> <div> <div class="some-class">sub-one</div> <div class="some-class">sub-two</div> </div> <div class="some-class">two</div> </div>
为什么之前的方法无效?
.some-class:last-child:会匹配任意父元素下的最后一个子元素且带有.some-class的元素,嵌套里的sub-two是它父级<div>的最后一个子元素,因此会被选中。.some-class:last-of-type:会匹配任意父元素下同类型(这里是<div>)元素中的最后一个且带有.some-class的元素,嵌套里的sub-two是它父级<div>下的最后一个<div>元素,因此也会被选中。
内容的提问来源于stack exchange,提问作者physicsboy
相关产品推荐
相关产品推荐

