rouan rouan - 1 month ago 7
CSS Question

Style the first column of a table differently if there is no <thead>

This is what I'm trying to achieve:

enter image description here

This is the markup I'm trying to style:

<h2>Table with no header</h2>
<table>
<tbody>
<tr>
<td>First column - bold</td>
<td>Second column</td>
</tr>
<tr>
<td>First column - bold</td>
<td>Second column</td>
</tr>
</tbody>
</table>

<h2>Table with a header</h2>
<table>
<thead>
<tr>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>First column - not bold</td>
<td>Second column</td>
</tr>
<tr>
<td>First column - not bold</td>
<td>Second column</td>
</tr>
</tbody>
</table>


Any ideas on how to achieve the desired outcome?

Answer

Do like this, where you use the direct child selector >, first-child and :not()

table > *:first-child:not(thead) td:first-child {
  font-weight: bold;
}

Sample

table > *:first-child:not(thead) td:first-child {
  font-weight: bold;
}
<h2>Table with no header</h2>
<table>
  <tbody>
    <tr>
      <td>First column - bold</td>
      <td>Second column</td>
    </tr>
    <tr>
      <td>First column - bold</td>
      <td>Second column</td>
    </tr>
  </tbody>
</table>

<h2>Table with a header</h2>
<table>
  <thead>
    <tr>
      <th>Header</th>
      <th>Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First column - not bold</td>
      <td>Second column</td>
    </tr>
    <tr>
      <td>First column - not bold</td>
      <td>Second column</td>
    </tr>
  </tbody>
</table>

Comments