Coloring every n’th rows in html table

In order to color every n’th row in html table we can use tr:nth-child . It does its jobs very well – targets child in specified element. Probably most common use for it possible to see in striped rows within a table:

This example was taken from here, so feel free to experiment with it. There pretty clear information there.

In my case the requirements were to distinguish every three lines.  So the cool thing about this nth-child thing is that, besides constants (like 5th row), even (even rows) and odd (odd rows) it is possible to provide formula !

Lets roll it then ! So we want to achieve something like this :

At this moment it is important to understand that our perception shifting towards blocks where we will color each line.

So we colored ones would be every third lines and also every second line and also every 1 lines (i.e.

div:nth-child(3n), div:nth-child(3n-1), div:nth-child(3n-2){
background: #CCCC99;

Regarding white ones it would be every 6th line, 5th line and also 4th line (I am sure you following the logic 🙂 ) :

div:nth-child(6n), div:nth-child(6n-1), div:nth-child(6n-2){
background: white

That is all, and as always code can be found here.  Happy coding and let me know what do you think in a comments !


Leave a Reply

Your email address will not be published. Required fields are marked *