Structural Pseudo-classes: nth-child and Friends

What Structural Pseudo-classes Do

These pseudo-classes select elements based on their position among sibling elements, without needing any class added to the markup at all.

nth-child() Basics

li:nth-child(odd) {
  background: #f5f5f5; /* classic striped table/list rows */
}
li:nth-child(3) {
  font-weight: bold; /* exactly the third item */
}
li:nth-child(3n) {
  color: red; /* every third item: 3, 6, 9... */
}

nth-child() accepts a keyword (odd/even), a specific number, or a formula like 3n (a multiple of 3) or 3n+1 (a multiple of 3, plus one).

first-child, last-child and only-child

SelectorMatches
:first-childAn element that is the first child of its parent
:last-childAn element that is the last child of its parent
:only-childAn element that is the only child of its parent

The -of-type Variants

p:first-of-type {
  font-size: 1.2rem;
}

:first-child only matches if the element is literally the first thing inside its parent, regardless of tag. :first-of-type instead matches the first element of that specific tag - useful when a paragraph is preceded by a heading, since p:first-child would fail to match in that case, but p:first-of-type still would.

Excluding Matches with :not()

li:not(:last-child) {
  border-bottom: 1px solid #eee; /* a divider between items, but not after the last one */
}

Combining structural pseudo-classes with :not() is a very common pattern for adding dividers or spacing between list items without affecting the very first or last one.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.