The last-child vs last-of-type selector in CSS

Let's say we have the following HTML:

<div>
    <h1>First h1</h1>
    <h1>Second h1</h1>
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>

If we want to target the last child of the div we will use:

div :last-child {
  color: red;
}
/*note the white space between div and :last-child*/

While if we want to target the last child of the div only if that child is a p element then we will have:

div p:last-child {
  color: red;
}

On the other side, last-of-type will target the last occurrence of that type of element. So, let's say we want to target the last occurrence of an h1 element in a div:

div h1:last-of-type {
  color: blue;
}

The last-of-type does not need to be the last child.

There are also many complementary alternatives for these selectors like : :first-of-type, :nth-last-of-type, first-child etc.

As usual Chris, from CSS Tricks, has a great article about this.

Below is a small example:

See the Pen
last-of-type vs last-child
by JS Craft (@js-craft)
on CodePen.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X