CodeBlanks Logo Icon CodeBlanks

:nth-child

CSS course · Intermediate · Lesson 14/98

Learn sibling selection with :nth-child.

What is :nth-child?

The :nth-child pseudo-class selects an element by its position among its siblings. You give a number or formula in parentheses.

For example, li:nth-child(2) grabs the second item in a list. tr:nth-child(3) matches the third row of a table. Counting starts at one, not zero.

This pseudo-class lets you style by position alone, without adding classes.

Zebra stripes with even and odd

Writing even in the parentheses matches siblings at even positions; odd matches odd positions. Even means even, odd means odd in English.

This is the standard way to create zebra-striped (alternating background) tables. With tr:nth-child(even) { background: #f5f5f5; }, every second row turns light gray and reading becomes easier.

Formulas with the n variable

:nth-child also accepts the an+b formula. Here n is a counter starting at zero.
  • 2n — even positions (same as even)
  • 2n+1 — odd positions (same as odd)
  • 3n — every third item

Formulas catch not single positions but regular intervals. This is handy for highlighting items at fixed steps in large lists.

Exercise Add zebra stripes to a table

Write a tr:nth-child(even) selector and add background: #f5f5f5 inside it. This makes every even row of the table light gray.

Show example solution
/* color the even rows */
tr:nth-child(even) {
  background: #f5f5f5;
}

Test yourself

  1. What does li:nth-child(2) match?

    li:nth-child(2) {
      font-weight: bold;
    }
    • The last item in the list
    • Every item in the list
    • The second item in the list
    • All items of the second list
    Show answer

    The second item in the list — Correct. :nth-child(2) selects the second item among siblings.

  2. Write the selector for odd-position items

    li____ {
      background: #fafafa;
    }
    Show answer
    li:nth-child(odd) {
      background: #fafafa;
    }
  3. Match each formula to the positions it selects

    :nth-child(1)
    First item
    :nth-child(2)
    Second item
    :nth-child(even)
    Even positions
    :nth-child(odd)
    Odd positions

All lessons in Intermediate