简体   繁体   English

如何针对除CSS中最后一个元素以外的所有元素?

[英]How to target all elements, except last one with css?

 .outer a:not(:last-of-type) { color: red; } 
 <div class="outer"> <a href="#">First</a> <a href="#">Second</a> <div> <a href="#">Third</a> </div> <a href="#">Fourth</a> <a href="#">Fifth</a> </div> 

Is there a way, to target all <a> 's inside div.outer (I can't think of way to target the one inside ) container? 有没有办法针对所有<a>的div.outer内部对象(我想不出一种针对内部的对象)容器? The only workaround I can think of is css: .outer a:not(.last) and adding .last to last <a> . 我能想到的唯一解决方法是css: .outer a:not(.last)并将.last添加到last <a> Any ideas? 有任何想法吗? Background: The main idea why I'm doing this, is that I have elements, which line near edge of container, so each of them has to have margin of 10 from right, except last one. 背景:执行此操作的主要想法是,我有一些元素,这些元素在容器边缘附近排成一行,因此每个元素的右边距必须为10,最后一个除外。 In this case, i don't have to type class margin-right-10 in each <a> , its just my own style I'm following. 在这种情况下,我不必在每个<a>键入class margin-right-10,这只是我遵循的我自己的样式。

.outer > a:not(:last-of-type), .outer > div a

同样有效,但无需更改标记。

If you number of levels inside .outer is known (or limited) you can extend selector like this: 如果.outer内部的级别数已知(或受限制),则可以扩展选择器,如下所示:

 .outer > * > a, .outer > a:not(:last-of-type) { color: red; } 
 <div class="outer"> <a href="#">First</a> <a href="#">Second</a> <div> <a href="#">Third</a> </div> <a href="#">Fourth</a> <a href="#">Fifth</a> </div> 

The part .outer > * > a makes sure that deeper links are also included into matched set. .outer > * > a可确保更深的链接也包含在匹配集中。

UPD. UPD。 Version #2 that also takes into consideration situation when the nested links are the last: 版本2还考虑了嵌套链接为最后链接时的情况:

 .outer > *:not(:last-child) > a, .outer > a:not(:last-child) { color: red; } 
 <div class="outer"> <a href="#">First</a> <a href="#">Second</a> <div> <a href="#">Third</a> </div> <a href="#">Fourth</a> <a href="#">Fifth</a> <div> <a href="#">Six</a> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM