CSS3: the nth-child pseudo-class

The CSS3 nth-child pseudo-class is a powerful CSS3 selector that solves many problems encountered by web developers while trying to stylize certain elements based on their position in the DOM tree. As its name says, this pseudo-class selects an element if this element is the nth-child of its parent. This kind of selector accepts four types of values:

  1. the keyword even (for even elements)
  2. the keyword odd (for odd elements)
  3. the n index, starting from 1
  4. the an+b formula, where n is a literal constant and a and b are numbers.

Some examples:

tr:nth-child(odd) {
  background: #eee;
}

The above code selects all tr elements that are odd. But we can also selects other indexes, like so:

tr:nth-child(4) {
   background: #eee;
}

This code selects the 4th tr element. If we want to perform a repeated selection, for example by selecting all tr elements that are multiples of 3, we can write this formula:

tr:nth-child(2n+1) {
  background: #eee;
}

Leave a Reply

Note: Only a member of this blog may post a comment.