css 如何从具有特定类的每一行之后开始为奇数表行着色?

kkbh8khc  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(124)

我的表中有节,所以有节标题行和常规行。我如何给两行中的一行着色,以便节标题后的下一行总是着色,就像下面的代码片段一样。我尝试使用+:nth-child的组合,但我无法使其工作。

table {
border-collapse: collapse;
}

.want {
  background-color: aquamarine;
}
<table>
  <tr class="table-header"><th>Blah</th><th>Blablablah</th></tr>
  <tr class="section-header"><th colspan="2">Section A</th></tr>
  <tr class="regular-row want"><td>A1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A2</td><td>Blah</td></tr>
  <tr class="regular-row want"><td>A3</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A4</td><td>Blah</td></tr>
  <tr class="regular-row want"><td>A5</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section B</th></tr>
  <tr class="regular-row want"><td>B1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>B2</td><td>Blah</td></tr>
  <tr class="regular-row want"><td>B3</td><td>Blah</td></tr>
  <tr class="regular-row"><td>B4</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section C</th></tr>
  <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section D</th></tr>
  <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
</table>
m1m5dgzv

m1m5dgzv1#

我建议使用嵌套的表或一系列tbody元素,这两种方法都可以简化操作。

table {
border-collapse: collapse;
}

tbody > tr:nth-child(even) {
  background-color: aquamarine;
}
<table>
  <thead>
    <tr class="table-header"><th>Blah</th><th>Blablablah</th></tr>
  </thead>
  <tbody>
    <tr class="section-header"><th colspan="2">Section A</th></tr>
    <tr class="regular-row want"><td>A1</td><td>Blah</td></tr>
    <tr class="regular-row"><td>A2</td><td>Blah</td></tr>
    <tr class="regular-row want"><td>A3</td><td>Blah</td></tr>
    <tr class="regular-row"><td>A4</td><td>Blah</td></tr>
    <tr class="regular-row want"><td>A5</td><td>Blah</td></tr>
  </tbody>
  <tbody>
    <tr class="section-header"><th colspan="2">Section B</th></tr>
    <tr class="regular-row want"><td>B1</td><td>Blah</td></tr>
    <tr class="regular-row"><td>B2</td><td>Blah</td></tr>
    <tr class="regular-row want"><td>B3</td><td>Blah</td></tr>
    <tr class="regular-row"><td>B4</td><td>Blah</td></tr>
  </tbody>
  <tbody>
    <tr class="section-header"><th colspan="2">Section C</th></tr>
    <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
    <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
    <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
  </tbody>
  <tbody>
    <tr class="section-header"><th colspan="2">Section D</th></tr>
    <tr class="regular-row want"><td>C1</td><td>Blah</td></tr>
    <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  </tbody>
</table>

相关问题