是否可以使用当前浏览器使用伪类来检测某个类的第一个和最后一个?

2022-01-10 00:00:00 css-selectors css pseudo-class

如果你有 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; }

相关文章