Tywele Tywele - 2 months ago 7
CSS Question

How to select the last element within an element regardless of type in CSS?

I want to select the last nested element regardless of the element's type.

Example:

<section>
<div></div>
<p></p>
<div></div> <-- I want this element
</section>
<section>
<div></div>
<p></p>
<a></a> <-- I want this element
</section>
<section>
<div></div>
<p></p>
<ul> <-- I want this element
<li></li>
</ul>
</section>


How do I get these elements?
:last-child
doesn't seem to do the trick and
:last-of.type
is also not helpful because I have to specify which type of element I want.

I want the last nested element of the
section
elements.

Answer

Use this:

section > *:last-child {
    // your custom css styles
}

Explanation:

This works because when you use:

> it select the immediate children

* this selects all the the elements

nth-child ensures that all the immediate children will be targetted (if you use nth-of-type that is not the case.

Comments