Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate color every two columns CSS/Javascript in a HTML table

I have a table that has dynamic columns added to it by Javascript. I am looking for a way to alternate the background color of every two columns, such as:

<table>
  <tr>
    <td>FIRST BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
  </tr>
</table>

So I know how to do alternate coloring with CSS (:nth-child(odd) etc..), but not how to have TWO columns the same color, then different color for the next two, and so on...

How can this be acheived? Javascript or jQuery solutions are also welcomed as I am using those already in the project, but CSS would be preferrable of course.

Thank you all!

like image 485
Nick Avatar asked Jan 28 '26 16:01

Nick


2 Answers

td
{
    background: #0f0;
}
td:nth-child(4n+3),
td:nth-child(4n+4)
{
    background: #f00;
}
like image 95
Duroth Avatar answered Jan 31 '26 06:01

Duroth


td{
  background: grey;
  }

td:nth-of-type(4n), td:nth-of-type(4n - 1){
  background: lime;
  }
<table>
  <tr>
    <td>FIRST BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>FIRST BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
    <td>SECOND BGCOLOR</td>
  </tr>
</table>
like image 44
Tom Avatar answered Jan 31 '26 06:01

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!