tyler
tyler

Reputation: 488

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

Upvotes: 2

Views: 62

Answers (2)

Johannes
Johannes

Reputation: 67738

In this case, for the nth-child use (4n+1), (4n+2), (4n+3) and (4n+4) (i.e. steps of four with an offset):

table {
  width: 100%;
}

table,
td {
  height: 20px;
}

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

tr:nth-child(4n+3) td,
tr:nth-child(4n+4) td {
  background-color: red
<table>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td></td>
  </tr>
</table>

Upvotes: 3

Denis Ross
Denis Ross

Reputation: 165

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>

Upvotes: 3

Related Questions