Striped Background Tables
To display striped background tables using CSS, use nth-child() CSS selector for table rows, and set background-color for even or odd rows. We may also set a color for even rows, and another color for odd rows.
The following is the CSS to set border-collapse value.
The syntax to set background-color for even numbered rows.
tr:nth-child(even) { background-color: #eee; }
The syntax to set background-color for odd numbered rows.
tr:nth-child(odd) { background-color: #eee; }
The syntax to set different background-color for even and odd numbered rows.
tr:nth-child(even) { background-color: #eee; } tr:nth-child(even) { background-color: #eea; }
Examples
1 Background Color for Even Numbered Table Rows
In the following example, we take a table with two columns, and four rows; and apply background color to even numbered rows in the table.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> table { width: 100%; } th { text-align: left; padding: 0.5em 0; } tr:nth-child(even) { background-color: #eee; } </style> </head> <body> <table> <thead> <tr> <th>Fruit</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>32</td> </tr> <tr> <td>Banana</td> <td>48</td> </tr> <tr> <td>Cherry</td> <td>75</td> </tr> <tr> <td>Mango</td> <td>69</td> </tr> </tbody> </table> </body> </html>
2 Background Color for Odd Numbered Table Rows
In the following example, we take a table with two columns, and four rows; and apply background color to odd numbered rows in the table.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> table { width: 100%; } th { text-align: left; padding: 0.5em 0; } tr:nth-child(odd) { background-color: #eee; } </style> </head> <body> <table> <thead> <tr> <th>Fruit</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>32</td> </tr> <tr> <td>Banana</td> <td>48</td> </tr> <tr> <td>Cherry</td> <td>75</td> </tr> <tr> <td>Mango</td> <td>69</td> </tr> </tbody> </table> </body> </html>
3 Different Background Color for Odd and Even Numbered Table Rows
In the following example, we take a table with two columns, and four rows; apply a background color to odd numbered rows, and a different color to even numbered rows, in the table.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> table { width: 100%; } th { text-align: left; padding: 0.5em 0; background-color: #adf; } tr:nth-child(even) { background-color: #eee; } tr:nth-child(odd) { background-color: #efe; } </style> </head> <body> <table> <thead> <tr> <th>Fruit</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>32</td> </tr> <tr> <td>Banana</td> <td>48</td> </tr> <tr> <td>Cherry</td> <td>75</td> </tr> <tr> <td>Mango</td> <td>69</td> </tr> </tbody> </table> </body> </html>
Conclusion
In this CSS Tutorial, we learned how to set background color for even and/or odd numbered rows in the table, and display a striped table, with examples.