How to style table rows differently by CSS nth-child selector?

Styling alternate HTML table rows differently

You may use the CSS nth-child selector for styling alternate table rows differently. Not only you may style alternative rows but also specify a different style for rows with the given number. For example, styling every 3rd or 4th row different to the other rows.

See the examples below where I will use odd, even and other numbers in the nth-child selector.

An example of styling alternate rows by odd value

In this example, the odd value is used in the nth-child selector. That means, the first (header), third, fifth rows will be assigned the style specified in the nth-child selector:

css nth child

See online demo and code

The following CSS class is used and applied to the HTML table:


A demo of using even value in nth-child selector

Only a few changes are made in above CSS along with using the even value in CSS nth-child selector in the tr instead of odd. Have a look at the output:

css nth child even

See online demo and code

The CSS:


You can see, the second row is assigned the style specified in nth-table tr:nth-child(even). Then, the row number fourth, sixth and so on.

A demo of styling every third row differently

As mentioned earlier, you may not only differentiate the alternate rows by using odd or even but also may specify a number to differentiate each 2nd, 3rd, 4th and so on rows.

For that, simply use the number in nth-child, for example,

nth-table-number tr:nth-child(3n)

See the online demonstration by clicking the image or link below:

css nth child third

See online demo and code

The CSS used for this demo:


You can see, every third row is assigned a different style. Get the complete code from the demo page.

A demo of start styling after certain rows

You may need to show differently styled rows in an HTML table after a certain number of rows. For example, showing first five rows in the same style and after that each odd or even row showing differently. You may use nth-child in an advanced way as follows to achieve that.

See this demo where I started styling odd rows differently after first four rows (the row count includes the table header that you may style differently).

css table nth child

See online demo and code

This is how the nth-child selector is used:


See the complete code on the demo page.

Similarly, you may use the nth-child selector in <td> or other elements for styling differently.