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
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
CodePudding user response:
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>
CodePudding user response:
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>