skip to Main Content
table, th, td {
  padding: 10px;
  border: 1px solid black;
  border-collapse: collapse;
}

th.red {
  background-color: red;
}
<table>
  <thead>
    <tr>
      <th>q</th><th class="red">w</th><th>e</th><th>r</th><th>t</th><th>y</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>q1</td><td>w1</td><td>e1</td><td>r1</td><td>t1</td><td>y1</td>
    </tr>
    <tr>
      <td>q2</td><td>w2</td><td>e2</td><td>r2</td><td>t2</td><td>y2</td>
    </tr>
  </tbody>
</table>

Is there a way to color a table column whose header has a certain class using CSS?

For example, in this table, to color the second column.

2

Answers


  1. You can simulate this by using an overflowing coloration that comes from the header

    table,th,td {
      padding: 10px;
      border: 1px solid black;
      border-collapse: collapse;
    }
    
    th.red {
      position: relative;
    }
    th.red:before {
      content: "";
      position: absolute;
      z-index: -1; /* a negative z-index */
      inset: 0 0 -999px; /* big value for the bottom */
      background: red;
    }
    table {
      overflow: hidden; /* hide the overflow of the pseudo element */
      isolation: isolate; /* make sure the coloration stay within the table (create a stacking context) */
      background: #f2f2f2;
    }
    <table>
      <thead>
        <tr>
          <th>q</th><th class="red">w</th><th>e</th><th>r</th><th>t</th><th>y</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>q1</td><td>w1</td><td>e1</td><td>r1</td><td>t1</td><td>y1</td>
        </tr>
        <tr>
          <td>q2</td><td>w2</td><td>e2</td><td>r2</td><td>t2</td><td>y2</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  2. You can also set a <colgroup>
    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col

    table, th, td {
      padding: 10px;
      border: 1px solid black;
      border-collapse: collapse;
    }
    
    .col_red {
      background-color: red;
    }
    <table>
      <colgroup>
        <col />
        <col class="col_red" />
       </colgroup>
      <thead>
        <tr>
          <th>q</th><th>w</th><th>e</th><th>r</th><th>t</th><th>y</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>q1</td><td>w1</td><td>e1</td><td>r1</td><td>t1</td><td>y1</td>
        </tr>
        <tr>
          <td>q2</td><td>w2</td><td>e2</td><td>r2</td><td>t2</td><td>y2</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search