Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

CSS: last-child of parent

Writer Andrew Henderson

:last-child works great when all of the "children" elements are the same (ie: all <p>'s or all <li>'s and the rule is applied to that type of child.

But how can I use CSS to select the last "child" element inside a parent which contains varying elements?

For instance, in this example, how could I apply a rule to the .parent to select the last object inside of it (the div)?

.parent:last-child { background-color: red; }
<div> <p>First child</p> <input type="text" placeholder="Second child" /> <div>Third child</div>
</div>
2

1 Answer

You can use .parent > *:last-child or just .parent > :last-child

An asterisk (*) is the universal selector for CSS. It matches a single element of any type. Omitting the asterisk with simple selectors has the same effect.

.parent > *:last-child { background-color: red;
}
<div> <p>First child</p> <input type="text" placeholder="Second child" /> <div>Third child</div>
</div>
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy