Search code examples
htmlcsshtml-tablecss-selectors

table apply css for row


I am working on html table where I need to add background color on rows but I don't have any class on the row. I am trying to use nth-child but I am not sure of my logic.

I want 2 rows to come in same background color and next 2 rows should come with background color2 like below image

enter image description here

tr:nth-child(2n) td {
  background-color: yellow
}

tr:nth-child(2n+1) td {
  background-color: pink
}
<table>
<tr><td>background should come as color1</td></tr>
<tr><td>background should come as color1</td></tr>

<tr><td>background should come as color2</td></tr>
<tr><td>background should come as color2</td></tr>

<tr><td>background should come as color1</td></tr>
<tr><td>background should come as color1</td></tr>

<tr><td>background should come as color2</td></tr>
<tr><td>background should come as color2</td></tr>
</table>
Above is giving background color to alternate row


Solution

  • tr {
      background-color: yellow
    }
    
    tr:nth-child(4n),
    tr:nth-child(4n - 1){
      background-color: red
    }
    <table>
    
    <tr><td>//background should come as color1</td></tr>
    <tr><td>//background should come as color1</td></tr>
    
    <tr><td>//background should come as color2</td></tr>
    <tr><td>//background should come as color2</td></tr>
    
    <tr><td>//background should come as color1</td></tr>
    <tr><td>//background should come as color1</td></tr>
    
    <tr><td>//background should come as color2</td></tr>
    <tr><td>//background should come as color2</td></tr>
    
    </table>