問題描述
如果你有 HTML:
<section class="column">
<p> Some Test </p>
<p> Some Test </p>
<p> Some Test </p>
</section>
<section class="column">
<p> Some More Test </p>
<p> Some More Test </p>
<p> Some More Test </p>
</section>
<section class="someotherclass">
<p> Some More Test </p>
<p> Some More Test </p>
<p> Some More Test </p>
</section>
和 CSS:
.column:last-child { background:red; }
http://jsfiddle.net/WYu24/
有沒有辦法讓 :last-child
選擇器選擇最后一次出現的類?
Is there a way to make the :last-child
selector pick up the last occurrence of a class?
推薦答案
目前在 CSS 中沒有快捷語法或偽類來查找具有某個類的第一個或最后一個子級.1
Currently there is no shortcut syntax or pseudo-class in CSS for finding the first or last child having a certain class.1
我使用一種覆蓋技術來設置具有特定類的第一個孩子的樣式,我在 this answer.但是,由于同級組合器的工作方式,這種技術不能應用于具有特定類的最后一個孩子.
I use an overriding technique to style the first child with a certain class, which I describe in heavy detail in this answer. However, due to how sibling combinators work, this technique cannot be applied for the last child having a certain class.
我不知道有任何純 CSS 方法來定位最后一個具有特定班級的孩子.您必須使用 JavaScript 或重組您的標記才能做到這一點.如果確實有一個這樣的元素,那么使用 jQuery,您可以簡單地使用 :last
選擇器添加一個類,然后您可以使用 CSS 設置樣式:
I do not know of any pure CSS way to target the last child having a certain class. You have to use JavaScript or restructure your markup in order to do that. If there is exactly one such element, then using jQuery you can simply use the :last
selector to add a class, which you can then style with CSS:
$('.column:last').addClass('last');
.column.last { background:red; }
jsFiddle 預覽
1 有一些在 Selectors 4 中提出了新的偽類,這將符合要求,但瀏覽器將在幾個月后或直到規范更穩定之前開始實施它,即便如此我們也不知道這些偽類是否-classes 會堅持下去,因為當前的語法看起來很尷尬:
1 There are some new pseudo-classes being proposed in Selectors 4 which would fit the bill, but browsers won't start implementing it for another few months or until the spec is more stable, and even then we don't know if these pseudo-classes are going to stick because the current syntax looks rather awkward:
:nth-last-match(1 of .column) { background:red; }
這篇關于是否可以使用當前瀏覽器使用偽類來檢測某個類的第一個和最后一個?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!