CSS: the nth-child selector in action

The nth-child structural pseudo-class is a powerful CSS3 selector that allows us to select elements based on their position in the DOM. Such position is a numerical index starting from 1. In this post I'll show you how this selector can be used to style elements in a more dynamic and flexible way.

The markup

We'll use the following markup in our example:

<ol id="bands">

  <li>Nirvana</li>
  <li>Iron Maiden</li>
  <li>Pennywise</li>
  <li>NoFX</li>
  <li>Bikini Kill</li>
  <li>Pantera</li>
  <li>Metallica</li>
  <li>Muse</li>
  <li>Rage Against The Machine</li>
  <li>The Doors</li>

</ol>

Even and odd elements

The nth-child selector accepts also two keywords, namely even and odd, to select only even and odd elements in a DOM structure. Example:

#bands li:nth-child(even) {
	background: #d34545;
	color: #fff;
	padding: 5px;
}

#bands li:nth-child(odd) {
	text-transform: uppercase;
	padding: 5px;
}

Formulas

The real power of this selector lies in its ability to accept formulas as its argument. A formula is made up of a base factor (e.g. 2), a coefficient (n) and an incremental index (e.g. +1). For example, if we want to select each 4th element in our list, we can write:

#bands li:nth-child(4n+1) {
    border-left: 0.5em solid #d34545;
    border-right: 0.5em solid #d34545;
    color: #338;
}

The index allows us to start from the very first element. If we omit such index by writing only 4n, the first element won't be included in the selection. An important thing to bear in mind is that the index may have a negative value. In this case, the index will be subtracted from the base factor. For example, if we want to select the last item in our list, we can use the following code:

#bands li:nth-child(11n-1) {

	border-bottom: 0.5em solid orange;
	text-transform: uppercase;

}

There are 10 items in our list, so 11 - 1 = 10 and we get the last one. You can see the final result below.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

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