How to Alternate Row Colors in a Table with CSS

This CSS trick blew my mind–for years before this was invented, I painstakingly did this manually in HTML, or used PHP code to alternate the lines in generated tables. And now it’s built-in! So cool!

This trick uses CSS to color rows based on what number row they are, or even if they are even or odd.

As an example, if I wanted to set the background color of a column to pale blue, I would use the following code:

table.bluerows tr:nth-child(even) {
     background-color: #afeeee;
}

With the following result:

This is the table header
This is row 1
This is row 2
This is row 3
This is row 4

Notice that this highlights the content rows starting with the first content row. This is because the table header row is counted as a row. If you want to change this behavior, try the following:

table.bluerows2 tr:nth-child(2n+3) {
     background-color: #afeeee;
}
This is the table header
This is row 1
This is row 2
This is row 3
This is row 4

The 2n in the CSS says to alternate every second row, and the 3 says to start with the third row.