Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing table row color per two rows

I have an HTML table and would like to change the row color every two rows, for two rows at a time. I don't mean selecting every other row using nth-child(even), which is all I keep seeing in my search engine results. I'm trying to set the background color of rows 1 and 2, then 5 and 6, then 9 and 10...and so on, leaving the other rows with the default white background.

I've tried using :nth-child(2n+b) and I don't think it's possible using that pseudo-selector. The tables are dynamically generated and will fluctuate in row count, so hard coding is not an option.

Is there some sort of JavaScript way to do this?

like image 957
abahler Avatar asked Sep 07 '25 17:09

abahler


1 Answers

It's definitely possible using CSS's :nth-child() notation:

tr:nth-child(4n + 1) td,
tr:nth-child(4n + 2) td {
    background-color: #ffa;
}

tr:nth-child(4n + 3) td,
tr:nth-child(4n + 4) td {
    background-color: #f90;
}

JS Fiddle demo.

like image 164
David Thomas Avatar answered Sep 10 '25 05:09

David Thomas