CodeBlanks Logo Icon CodeBlanks

Zebra stripes

CSS course · Intermediate · Lesson 85/98

Learn zebra-striped tables with :nth-child(even).

What are zebra stripes?

Zebra stripes give table rows alternating background colors. The eye tracks even and odd rows separately, preventing lost lines in long lists. In CSS this is done with :nth-child(even) and :nth-child(odd).

Example: tr:nth-child(even) { background: #f1f5f9; }. This makes even-numbered rows light gray; odd rows keep the default color. In long sales reports it improves readability.

Even versus odd

:nth-child(even) picks rows 2, 4, 6...; :nth-child(odd) picks 1, 3, 5.... You decide which gets the dark and which the light shade.

Many choose light gray for even rows, but flipping them gives the same effect. What matters is that the two row types stand out visually. The zebra name comes from this: like a horse's black-and-white pattern.

Exercise Add zebra stripes to a user list

For a table with class .kullanicilar, add zebra stripes: write background: #f1f5f9; on the .kullanicilar tr:nth-child(even) selector. Also add padding: 10px; on the .kullanicilar td, .kullanicilar th selector.

Show example solution
open a .kullanicilar tr:nth-child(even) selector and write background: #f1f5f9; inside. Then open a .kullanicilar td, .kullanicilar th selector and write padding: 10px; inside.
Example solution:
.kullanicilar tr:nth-child(even) {
  background: #f1f5f9;
}
.kullanicilar td, .kullanicilar th {
  padding: 10px;
}

Test yourself

  1. Which selector targets even-numbered rows?

    /* the ? selector gives a background to even rows */
    • tr:nth-child(odd)
    • tr:even
    • tr.even
    • tr:nth-child(even)
    Show answer

    tr:nth-child(even) — Correct! tr:nth-child(even) targets even-numbered rows.

  2. Selector that targets even rows

    ____ {
      background: #f1f5f9;
    }
    Show answer
    tr:nth-child(even) {
      background: #f1f5f9;
    }
  3. Match the pseudo-classes

    :nth-child(even)
    even rows
    :nth-child(odd)
    odd rows
    :hover
    on hover
    :first-child
    first item

All lessons in Intermediate