Home > OS >  How can I color odd-numbered table rows starting after each row with a particular class?
How can I color odd-numbered table rows starting after each row with a particular class?

Time:01-28

I have sections in my table, so there are section-header rows and regular-rows. How can I color one in two rows, so that the next row after the section-header is always colored, like in the following snippet. I'm trying using a combination of and :nth-child, but I can't make it work.

table {
border-collapse: collapse;
}

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

CodePudding user response:

I suggest either nested tables or a series of tbody elements. Either would make this simple.

table {
border-collapse: collapse;
}

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

  •  Tags:  
  • css
  • Related