[英]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>
有沒有辦法針對所有<a>
的div.outer內部對象(我想不出一種針對內部的對象)容器? 我能想到的唯一解決方法是css: .outer a:not(.last)
並將.last添加到last <a>
。 有任何想法嗎? 背景:執行此操作的主要想法是,我有一些元素,這些元素在容器邊緣附近排成一行,因此每個元素的右邊距必須為10,最后一個除外。 在這種情況下,我不必在每個<a>
鍵入class margin-right-10,這只是我遵循的我自己的樣式。
.outer > a:not(:last-of-type), .outer > div a
同樣有效,但無需更改標記。
如果.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>
.outer > * > a
可確保更深的鏈接也包含在匹配集中。
UPD。 版本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.