table 应用 css 行

table apply css for row

我正在处理 html table,我需要在行上添加背景颜色,但我没有在行上添加任何 class。我正在尝试使用第 nth-child,但我不确定我的逻辑。

我希望 2 行具有相同的背景颜色,接下来的 2 行应具有如下图所示的背景颜色 2

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>
以上是为备用行提供背景颜色

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>

在这种情况下,对于 nth-child 使用 (4n+1)(4n+2)(4n+3)(4n+4)(即带有偏移量的四步):

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>