CSS pseudo-classPseudo-classes

:last-child

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

On this page

Example

#
CSS
.crumbs li:not(:last-child)::after {
  content: "/";
  margin: 0 8px;
  color: #71717a;
}

.crumbs li:last-child {
  color: #fff;
  font-weight: 600;
}
Preview

Definition and usage

#

The :last-child pseudo-class is the mirror image of :first-child: it selects the element standing at the very end of its parent. A typical example is removing the bottom margin of the last paragraph in a card, so the gap from the edge is the same on every side.

The same trap applies as with :first-child. The selector p:last-child only works when the paragraph is truly the last child. If a button or a footer follows it, nothing gets selected. That’s where :last-of-type helps.

The pseudo-class stays live. When a script appends a new element to the end of a list, the previous last element stops matching, and the style moves to the new element with no change to the CSS at all.

Syntax

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

Example selectors

#
  • li:last-child

    The last bullet of the list, because it closes out its parent.
  • p:last-child

    Nothing lights up: the article’s last child is the button.
  • p:last-of-type

    The last paragraph among paragraphs, even if another element follows it.
  • li:not(:last-child)

    Every bullet except the last, for example for separators inserted between elements.

Example selectors in practice

#

li:last-child

The last bullet of the list, because it closes out its parent.
li:last-child { background: #7c3aed; color: #fff; }

p:last-child

Nothing lights up: the article’s last child is the button.
p:last-child { background: #7c3aed; color: #fff; }

p:last-of-type

The last paragraph among paragraphs, even if another element follows it.
p:last-of-type { background: #7c3aed; color: #fff; }

li:not(:last-child)

Every bullet except the last, for example for separators inserted between elements.
li:not(:last-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

#
  • In cards and dialogs, zero out the bottom margin of the last child (.card > :last-child { margin-bottom: 0 }). The gap from the bottom edge will match the top one.
  • The simplest way to add separators between elements is li:not(:last-child)::after. The last element won’t get a stray character.
  • When different elements can appear at the end of the parent, :last-of-type is more resilient than :last-child.

Related entries

#

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