Select the last item from already selected items in pure css

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

How can I get only a pair of 'z' , if I did not know its index in the DOM structure! . or how to get the last child of the '.area' class? I see that this CSS3 gets the last element , but it does not work in my case, because I have another parent element in the parent element.

p.area:last-child does not work!

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

The selector is as follows: 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 
+4
source share
2 answers

You cannot do this without javascript. Here is a quote from the W3C specification :

Offline text and other non-element nodes are not taken into account when calculating the position of an element in the list of children of its ancestor.

Pseudo-classes of target elements that cannot be targeted by combinators or simple selectors such as id or class. These types of pseudo-classes are called Structural pseudo-classes . They will ignore the fact that the element has a class, and simply use the DOM to determine the correct element to target.

In this case, your only options are explicit targeting with nth-child or javascript.

+6
source

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

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

For browser support, see here .

0
source

Source: https://habr.com/ru/post/1497324/


All Articles