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

℡╲_俬逩灬. 提交于 2019-12-28 07:03:11

问题


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?


回答1:


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


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


来源:https://stackoverflow.com/questions/10230416/is-it-possible-using-current-browsers-to-use-pseudo-classes-to-detect-first-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!