Search code examples
htmlcsshtml-table

How can you use css to style all <td> elements in a table when one of the <td> elements has a certain class?


I need to highlight an entire row of in a table when one of the elements contains a certain class. Example:

.whole-row-red-background {
  background-color: red;
}
<table>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td class='whole-row-red-background'></td>
      <td></td>
      <td></td>
    </tr>
  </tbody </table>

In the example above, only the first cell (the first td) of the second row in the table is set with a red background. Under this scenario (first <td> in the row has this class) I need all <td> elements in the row to have a red background.


Solution

  • You could use the general sibling selector. More info here: https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

    Here is your updated snippet:

    .whole-row-red-background {
      background-color: red;
    }
    
    .whole-row-red-background ~ td {
      background-color: red;
    }
    <table>
      <tbody>
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td class='whole-row-red-background'></td>
          <td></td>
          <td></td>
        </tr>
      </tbody </table>