Select last element from already selected elements

2019-06-27 22:59发布

问题:

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

回答1:

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.



回答2:

you should use nth child, see here how it works. In your case, it should be:

p.area:nth-child(5){
your style here;
}

For browser support look here.