Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

css - Is it possible using current browsers to use pseudo-classes to detect first and last of a certain class?

If you have the 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>

and CSS:

.column:last-child { background:red; }

http://jsfiddle.net/WYu24/

Is there a way to make the :last-child selector pick up the last occurrence of a class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Currently there is no shortcut syntax or pseudo-class in CSS for finding the first or last child having a certain class.1

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.

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 preview


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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...