从纯css中的已选择元素中选择最后一个元素 [英] Select last element from already selected elements in pure css

查看:700
本文介绍了从纯css中的已选择元素中选择最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的东西像jquery :最后选择器,但在纯css。



'z'段落,如果我不知道其在DOM结构中的索引!
或如何获得类'.area'的最后一个孩子?
我看到这个 CSS3获取最后一个元素,但它不工作在我的情况下,因为我在父元素中有另一个孩子。



p.area:last-child donesn't work! / p>

我发现一个解决方案,当我们知道有多少元素将与类 .area



选择器看起来像这样: p.area〜p.area〜p.area
但是当我们不知道...我想...
just for fun =)

 < div& 

< h1>这是一个标题< / h1>
< p class =>第一段。< / p>
< p class =area> x段。< / p>
< p class =area>第y段。< / p>
< p class =area> z段落。< / p>
< p class =>最后一段。< / p>

< / div


解决方案

你不能没有javascript。以下是 W3C规格的报价:



计算元素在
的子元素列表中的位置时,独立文本和其他非元素节点不计算在内父类。


伪类使用组合器或简单选择器(如id或类)无法定位目标元素。这些类型的伪类称为结构伪类。它们将忽略元素上有一个类,只需使用DOM来确定要定位的正确元素。



您的唯一选项是使用nth-子级或JavaScript。


I want something like jquery :last selector, but in pure css.

How can i get only 'z' paragraph, if i didn't know its index in DOM structure!. or how get last child of class '.area'? I see this CSS3 get last element , but it doesnt work in my case, because i have another childs in parent element.

p.area:last-child donesn't work!

I found a solution, when we know how many elements will be with class .area.

Selector looks like this: p.area ~ p.area ~ p.area But when we didn't know ... I think... just for fun =)

<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

解决方案

You cant do it without javascript. Here is a quote from 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.

Pseudo-classes target elements that can't be targeted with combinators or simple selectors like id or class. These types of pseudo classes are called "Structural Pseudo Classes". They will ignore the fact that there is a class on the element and simply use the DOM to determine the correct element to target.

Your only options are explicit targeting with nth-child or javascript in this instance.

这篇关于从纯css中的已选择元素中选择最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆