Is it possible using current browsers to use pseudo-classes to detect first and last of a certain 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; }
这篇关于是否可以使用当前浏览器使用伪类来检测某个类的第一个和最后一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以使用当前浏览器使用伪类来检测某个类


基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01