Back to course

Lesson 42: Pseudo-Classes: Structural Child Selectors (nth-child)

CSS Mastery: From Zero to Hero in 100 Lessons

42. Pseudo-Classes: Structural Child Selectors

Structural pseudo-classes allow you to select elements based on their position within their parent container, even if they don't have a unique class or ID.

1. :first-child and :last-child

Selects the first or last element among a group of siblings.

html

  • First Item
  • Second Item
  • Last Item

css li:first-child { font-weight: bold; /* Targets the 'First Item' li */ }

li:last-child { border-bottom: none; /* Often used to remove borders/margins from the last item */ }

2. :nth-child(n)

This is the most powerful structural selector. It selects elements based on a numeric pattern where n starts at 0 or 1.

Targeting Specific Items

  • li:nth-child(3): Selects the third list item.

Targeting Odd/Even Rows (Striping)

  • li:nth-child(odd)
  • li:nth-child(even)

css /* Zebra-striping tables or lists */ .data-row:nth-child(even) { background-color: #eee; }

Targeting Every Nth Item (Formulas)

You can use the formula An + B where A is the cycle size, and B is the offset.

  • li:nth-child(3n): Selects the 3rd, 6th, 9th, etc.
  • li:nth-child(3n + 1): Selects the 1st, 4th, 7th, etc.