CSS :nth-child selector

The :nth-child CSS selector (or pseudo-class) can be pretty useful, for example to select odd and even rows in a table.

We apply a variety of styles to show some different effects.

Setting Up

The examples that follow use this HTML snippet:

<table>
  <tbody>
    <tr><td>Row 1</td></tr>
    <tr><td>Row 2</td></tr>
    <tr><td>Row 3</td></tr>
    <tr><td>Row 4</td></tr>
    <tr><td>Row 5</td></tr>
  </tbody>
</table>

Examples

Even Rows

Example with even rows (pink background):

tr:nth-child(2n) {
  background-color: pink;
}
Row 1
Row 2
Row 3
Row 4
Row 5

Odd Rows

Example with odd rows (bold text):

tr:nth-child(2n+1) {
  font-weight: bold;
}
Row 1
Row 2
Row 3
Row 4
Row 5

Specific Numbers

Example with a numbered element (bold text and pink background):

tr:nth-child(2) {
  background-color: pink;
  font-weight: bold;
}
Row 1
Row 2
Row 3
Row 4
Row 5

Spans of Elements

Example with a span of elements from the beginning to the second element inclusive (italic text and yellow background):

tr:nth-child(-n+2) {
  background-color: yellow;
  font-style: italic;
}
Row 1
Row 2
Row 3
Row 4
Row 5

Example with a span of elements from the second to the last inclusive (bold text and yellow background):

tr:nth-child(n+2) {
  background-color: yellow;
  font-weight: bold;
}
Row 1
Row 2
Row 3
Row 4
Row 5

Read more

For more documentation and examples, see:

Tags: