css - 从纯 css 中已选择的元素中选择最后一个元素

标签 css css-selectors

我想要类似 jquery :last 选择器的东西,但在纯 css 中。

如果我不知道它在 DOM 结构中的索引,我怎么能只得到“z”段呢!。 或者如何获得“.area”类的最后一个 child ? 我看到这个 CSS3 get last element ,但它在我的情况下不起作用,因为我在父元素中有另一个 child 。

p.area:last-child 不工作!

当我们知道类 .area 有多少元素时,我找到了解决方案。

选择器看起来像这样:p.area ~ p.area ~ p.area 但是当我们不知道...我想... 只是为了好玩 =)

<div>

<h1>This is a heading</h1>
<p class="">The first paragraph.</p>
<p class="area">The x paragraph.</p>
<p class="area">The y paragraph.</p>
<p class="area">The z paragraph.</p>
<p class="">The last paragraph.</p>

</div

最佳答案

没有javascript你做不到。这是来自 the W3C spec 的引述:

Standalone text and other non-element nodes are not counted when calculating the position of an element in the list of children of its parent.

伪类目标元素无法使用组合器或简单选择器(如 id 或 class)作为目标。这些类型的伪类称为“Structural Pseudo Classes”。他们会忽略元素上有一个类这一事实,而只是使用 DOM 来确定要定位的正确元素。

在这种情况下,您唯一的选择是使用 nth-child 或 javascript 进行显式定位。

关于css - 从纯 css 中已选择的元素中选择最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261892/

相关文章:

html - IE9 : rotated background images become skewed

javascript - iOS 设备处理 :hover pseudo-class? 的默认方式是什么

javascript - 如何获取所有可能有祖先的元素,而它们的所有祖先都没有指定的类?

css - :after in a <img> element unexpected result

html - 边框折叠的表格 - 右边框溢出底部

javascript - JQuery 高度不返回准确高度

javascript - 滚动到 ng-repeat 中数组中最后添加的记录

CSS 用于 DIV 的斜坡弯 Angular

css - 调用 :hover selector 中的 <div>

python-3.x - UnexpectedTagNameException : Message: Select only works on <select> elements, 不是 <li> 使用 Selenium 从下拉列表中选择 li 元素时出错