→ :nth-child

30 November 2009

For my new projects page, I wanted the background color of each box to change into one of six pre-selected colors on hover. I also wanted an arbitrary number of boxes, so the colors needed to repeat.

I could easily do this using a template language by giving each li a unique class then styling thoses classes, but that's lame. Instead I used CSS3's :nth-child, which works in current versions of Chrome, Safari, and Firefox.

The CSS for the first two boxes is as follows:

.row > a:nth-child(6n+1):hover {
  background-color: #FFFF00;
}

.row > a:nth-child(6n+2):hover {
  background-color: #FF0000;
}

The 6n+1 means "the first instance and every sixth instance thereafter." So 6n+2 is the second a which is a child of .row and every sixth a after that.

In this manner we also define 6n+3 through 6n+6.

If there were only four boxes, I'd have 4n+1 through 4n+4. In fact, to achieve the step-like effect with the boxes I style every first and third box differently using 4n+1 and 4n+3:

.row > a:nth-child(4n+1) {
  margin-top: 40px;
}

.row > a:nth-child(4n+3) {
  margin-top: 0;
}

Finally, I give the first a some extra padding:

.row > a:first-child {
  padding-left: 20px;
}

Which I could have written as:

.row > a:nth-child(1) {
  padding-left: 20px;
}

For more (somewhat obtuse) information, see Sitepoint's Understanding :nth-child Pseudo-class Expressions documentation.