Hit enter after type your search item

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 is different from 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

HTML and CSS:

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

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)

css nth child third

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

This is how the nth-child selector is used:


 

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

This div height required for enabling the sticky sidebar