有没有办法用CSS选择特定元素的最后出现?
这是一个例子:DEMO
我尝试过
last-child
但这不是我想要的。我用过这个课程:
HTML:
<ul>
<li><span>test</span></li>
<li>
<span>test</span>
<span>test</span>
</li>
</ul>
<div>
<span>test</span>
<span>test</span>
</div>
<p>
<span>test</span>
<span>red</span>
</p>
CSS:
span:last-child{
color:red;
font-weight:bold;
}
我希望最后一个带有“红色”内容的
span
是红色的。我怎样才能用CSS做到这一点?
更新: 对于具有相同父元素的元素,有一个使用
last-of-type
的解决方案。但不同的父母呢?
这是从我的博客中获取的解决方案:https://css-tip.com/last-element-dom/
span {
&:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
color: red;
font-weight: bold;
}
}
<ul>
<li><span>test</span></li>
<li>
<span>test</span>
<span>test</span>
</li>
</ul>
<div>
<span>test</span>
<span>test</span>
</div>
<p>
<span>test</span>
<span>red</span>
</p>
一个更复杂的例子:
span {
&:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
color: red;
font-weight: bold;
}
}
<div>Some content</div>
<div>
<span>Some content</span>
<span>
<span>Some content</span>
<span>Some content</span>
<span>Some content</span>
</span>
<span>Some content</span>
<span>Some content</span>
</div>
<div>
<span>Some content</span>
<span>Some content</span>
</div>
<span>
<span>Some content</span>
<span>Some content</span>
</span>
<div>
<span>
<span>Some content</span>
<span>Some content</span>
</span>
<span>
<span>Some content</span>
<span>Some content</span>
<span>Some content</span>
</span>
<span>
<span>Some content</span>
<span>Some content</span>
<span>Some content
<span>Some content</span>
<span>Some content</span>
</span>
<span>
<span>
<span>
<span>Some content</span>
<span>Some content</span>
<span>Some content</span>
</span>
</span>
</span>
<span>
<span>Some content</span>
<span>Some content</span>
<span>Some content</span>
</span>
</span>