HTML & CSS Tip of the Week

:first-child and :last-child

Published on


The :first-child and :last-child pseudo-classes are incredibly useful for styling elements based on their position within their parent container without needing to add extra classes (or resorting to JavaScript).

Their names basically cover what they do, only selecting an element that is either the first or last child.

Common use cases

Adding a border between items

When we have a navigation and need a border between each item, we can :not(:last-child) to add a border to the bottom of every item, except the last one:

.nav__list-item:not(:last-child) {
  padding-block-end: 1rem;
  border-block-end: 1px solid #333;
}

Different border radius for grouped buttons

.button-group {
  display: flex;
}

.button-group > button {
  border-radius: 0;
  border: 2px solid #333;
  border-inline-end-width: 0px;
}

.button-group > button:first-child {
  border-radius: 100vw 0 0 100vw;
}

.button-group > button:last-child {
  border-radius: 0 100vw 100vw 0;
  border-inline-end-width: 2px;
}

Important things to remember

They select ANY element type: :first-child doesn’t mean “first paragraph” or “first div” - it means the very first child element, whatever it is.

So, in this example, p:first-child wouldn’t select anything, because none of the paragraphs are a first child.

<article>
  <h2>Title</h2> <!-- This is :first-child -->
  <p>First paragraph</p>
  <p>Second paragraph</p> <!-- This is :last-child -->
</div>

Dive deeper