CSS pseudo-classPseudo-classes

:first-child

Matches an element that is the first child of its parent.

On this page

Example

#
CSS
.list li {
  padding: 8px 0;
  border-top: 1px solid #3f3f46;
}

.list li:first-child {
  border-top: 0;
}
Preview

Definition and usage

#

The :first-child pseudo-class selects the element standing at the very start of its parent. li:first-child is the first bullet of every list on the page, because every list has some first bullet. Only elements count; text before them doesn’t matter.

The most common trap: the selector checks whether the element is the first child at all, not the first element of a given type. If a heading sits before the first paragraph in an article, p:first-child won’t match anything, because the heading is the first child. For cases like this, use :first-of-type, which only counts elements with the same tag.

The pseudo-class is handy for removing unnecessary spacing and borders at the edges: the first list item with no top line, the first card with no margin. :first-child means the same thing as :nth-child(1), and its mirror image is :last-child.

Syntax

#
Syntax
selector:first-child { property: value; }

Example selectors

#
  • li:first-child

    The first bullet of the list, because it stands right at the start of its parent.
  • p:first-child

    Nothing lights up: the article’s first child is h4, not a paragraph.
  • p:first-of-type

    The fix: the first paragraph among paragraphs, regardless of the heading before it.
  • li:not(:first-child)

    Every bullet except the first. Handy for a divider line between consecutive elements.

Example selectors in practice

#

li:first-child

The first bullet of the list, because it stands right at the start of its parent.
li:first-child { background: #7c3aed; color: #fff; }

p:first-child

Nothing lights up: the article’s first child is h4, not a paragraph.
p:first-child { background: #7c3aed; color: #fff; }

p:first-of-type

The fix: the first paragraph among paragraphs, regardless of the heading before it.
p:first-of-type { background: #7c3aed; color: #fff; }

li:not(:first-child)

Every bullet except the first. Handy for a divider line between consecutive elements.
li:not(:first-child) { background: #7c3aed; color: #fff; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Before using p:first-child, check what actually stands at the start of the parent. :first-of-type is often the safer choice.
  • For an element that is the only child, there’s :only-child. It matches when the element is simultaneously first and last.
  • Instead of zeroing out the border of the first element, you can write li + li { border-top: … } or li:not(:first-child) directly.

Related entries

#

Spotted a mistake or missing an example? Write to us.