Skip to the page
css reference · selectors

CSS :nth-child() / :not()

type
pseudo-classes
applies to
any element
inherits
n/a
common values
:nth-child(2), :nth-child(odd), :nth-child(3n+1), :last-child, :not(.active)

Where it goes

In the selector, after the tag or class it narrows. Counting starts at 1 and counts every sibling, whatever its tag. :nth-of-type counts only siblings with the same tag.

Example

tr:nth-child(odd) { background: #f5f5f7; }
.card:nth-child(3n) { margin-right: 0; }
li:not(:last-child) { border-bottom: 1px solid #ddd; }
.btn:not(.primary) { background: transparent; }

Common mistakes

  • Expecting :nth-child(2) to mean "the second .card." It means "the parent's second child, if it is also a .card." A heading before the cards shifts everything by one. :nth-of-type fixes it.
  • Starting the count at 0. The first child is 1. 3n+1 gives 1, 4, 7.
  • Using :not(:last-child) for spacing when items can be added out of order. It still works, but gap on the parent is simpler and never leaves a stray divider.

Related

Updated 24 October 2026. Practice it in the css route, or read more on MDN.