Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: last-child of parent

: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 class="parent">
  
  <p>First child</p>
  <input type="text" placeholder="Second child" />
  <div>Third child</div>
  
</div>
like image 731
MultiDev Avatar asked Jan 23 '17 18:01

MultiDev


People also ask

What is last child in CSS?

The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

How do you select the last tr in CSS?

In this CSS :last-child example, the last row (ie: the last <tr> tag) will have a yellow background color. All other rows in the table will not be styled by the :last-child selector.


1 Answers

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 class="parent">    <p>First child</p>    <input type="text" placeholder="Second child" />    <div>Third child</div>  </div>
like image 52
Nenad Vracar Avatar answered Sep 21 '22 14:09

Nenad Vracar