How to set alternate table row color in CSS?

When we have large tables with a lot of data, it becomes important to provide better readability to the users. One way to achieve this is by highlighting the alternate rows of the table. It can significantly improve the readability. Such tables are called zebra-striped tables.

Table Header Table Header Table Header
Table cell Table cell Table cell
Table cell Table cell Table cell
Table cell Table cell Table cell
Table cell Table cell Table cell

To set alternate table row colors, we have to first select all the alternate rows of the table. To do that we can use the :nth-child() selector. The :nth-child() selector can select all even or odd rows of the table.


1. Highlight all even rows of the table:

To highlight all the even rows use tr:nth-child(even). This will select all rows at even positions like 2, 4, 6, and so on.

Example:

tr:nth-child(even){
   background: #dedede;
}

2. Highlight all odd rows of the table:

To highlight all the odd rows use tr:nth-child(odd). This will select all rows at odd positions like 1, 3, 5, and so on.

Example:

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

You can read more about nth-child() and other similar selectors in CSS Pseudo Classes article.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.