SyntaxStudy
Sign Up
CSS :first-child and :last-child
CSS Beginner 4 min read

:first-child and :last-child

:first-child and :last-child

:first-child selects an element that is the first child of its parent. :last-child selects the last child. Use them to remove borders or margins at edges.

Example
/* Remove border from last list item */
.list-item {
  border-bottom: 1px solid #ddd;
}
.list-item:last-child {
  border-bottom: none;
}

/* Style first paragraph differently */
article p:first-child {
  font-size: 1.125rem;
  font-weight: 500;
}

/* Remove margin on first and last */
.card > *:first-child { margin-top: 0; }
.card > *:last-child  { margin-bottom: 0; }
Pro Tip

Use :first-child / :last-child to remove edge margins and borders rather than adding a "first" or "last" class in HTML.