Skip to content

CSS Tutorial CSS Pseudo-classes

CSS :first-child and :last-child

Lesson 119 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

:first-child matches an element that is the first child of its parent. :last-child matches the last.

index.html
HTML
<style>
  ul { list-style: none; padding: 0; width: 220px; border: 1px solid #ccc; }
  li { padding: 10px 14px; border-bottom: 1px solid #ccc; }
  li:last-child { border-bottom: 0; }
  li:first-child { font-weight: bold; background: #fdf2e9; }
</style>
<ul>
  <li>First item (bold)</li>
  <li>Middle item</li>
  <li>Last item (no bottom border)</li>
</ul>

The classic use: no border on the last item

Items usually get a divider line. The last one should not, since the container already has a border. :last-child handles it without any extra class.

Other helpful ones

SelectorMatches
:first-childThe first child of its parent
:last-childThe last child of its parent
:only-childThe only child
:first-of-typeThe first element of its tag among siblings
:last-of-typeThe last of its tag
style.css
CSS
/* Space between siblings but not before the first */
li + li { margin-top: 8px; }

/* Remove the top margin of the first paragraph in a card */
.card > p:first-child { margin-top: 0; }

first-child vs first-of-type

p:first-child means “a p that is the first thing in its parent”. If an h2 comes first, no paragraph matches. p:first-of-type means “the first p among its siblings”, whatever comes before. If a selector surprises you, that is the usual reason.

warning
A comment or text node in front
HTML comments and whitespace do not count, but another element does. If something is inserted before your element, it is no longer :first-child.