DEV Community

Daniel - JS Craft
Daniel - JS Craft

Posted on

8 2

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>
Enter fullscreen mode Exit fullscreen mode

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*/
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

first published on http://www.js-craft.io/blog/the-last-child-vs-last-of-type-selector-in-css/

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs