Course contentsShow
← Web Development
Lesson 126 of 2,9823. CSS FundamentalsFree lesson

Structural Pseudo-Classes: :first-child and :last-child

Select elements based on their position among siblings without adding extra classes.

Structural Pseudo-Classes: :first-child and :last-child

You'll learn how to target the first or last element among siblings without adding extra classes to your HTML.

The Core Idea

Sometimes you need to style the first or last item in a group differently—like removing the top border from the first card or adding extra spacing after the last paragraph. You could add a class like class="first" or class="last" to your HTML, but that's extra work and breaks if you reorder elements. Instead, CSS gives you structural pseudo-classes that automatically target elements based on their position.

How :first-child and :last-child Work

:first-child selects an element only if it's the first child of its parent. Similarly, :last-child targets the last child.

/* Remove margin from the first paragraph */
p:first-child {
  margin-top: 0;
}

/* Add extra spacing after the last paragraph */
p:last-child {
  margin-bottom: 2rem;
}

Think of a family photo where kids line up by age. The :first-child is always the one on the left end, and :last-child is on the right—no matter how many siblings there are.

Practical Example

/* Style the first list item differently */
li:first-child {
  font-weight: bold;
  color: navy;
}

/* Add a bottom border to all list items except the last */
li {
  border-bottom: 1px solid gray;
}

li:last-child {
  border-bottom: none;
}

This automatically styles your first and last items correctly, even if you add or remove items from the list later.

Key Takeaway: Use :first-child and :last-child to target elements by their position among siblings, keeping your HTML clean and your styles adaptable to change.