How to Style Alternate Table Rows Color Using CSS

Last Updated on February 13, 2021 by Roshan Parihar

In this tutorial, learn how to style alternate table rows color using CSS. The short answer is: use the CSS property :nth-child() selector to apply and highlight the background color of alternate table rows.

You can pass the numbers (like 1,2,3…) or number expression (like n, n+1, 2n+1….) or any expressions or even/odd as the argument of :nth-child(). Let’s find out with the examples given below.

How to Style Alternate Table Rows Color of Using CSS

To apply the style or highlight the alternate table row, you have to first decide table even rows or odd rows. Let’s see for each type of the table row even or odd below.

Style Alternate Even Table Rows

If you want to style and highlight the even rows of a table, you have to pass the argument ‘even’ or number expression ‘2n+2’ as the argument of the :nth-child selector.

Below is the example to style and apply the background CSS property using the even rows.

Output

Sr. No. Cricketer Name Score
1 Sunil Narayan 123
2 Akshar Patel 87
3 Sarfaraz Husain 34
4 Kunal Pandya 93
5 Hardik Pandya 87
6 Neel Patel 90

The above example shows the styled alternate table rows using CSS.

Highlight Alternate Odd Rows

If you want to style, highlight the background color of the odd rows of a table, you have to pass the argument ‘odd’ or number expression ‘2n+1’ as the argument of the :nth-child selector.

Below is the example to apply the background-color CSS property using the odd rows.

Output

Sr. No. Cricketer Name Score
1 Sunil Narayan 123
2 Akshar Patel 87
3 Sarfaraz Husain 34
4 Kunal Pandya 93
5 Hardik Pandya 87
6 Neel Patel 90

The above example shows the highlighted odd rows using CSS. You can change the color as per your requirements.

You May Also Like to Read