Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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?

like image 203
rouan Avatar asked Oct 31 '16 19:10

rouan


People also ask

How do I target the first column of a table in CSS?

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice. For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

Which selector add the style to the first row of table?

The ::first-line selector is used to add a style to the first line of the specified selector. Note: The following properties can be used with ::first-line: font properties.

Can an HTML table have different columns in different rows?

Cells within HTML tables can span multiple rows and multiple columns. The cell default is one row and one column. However, with the ROWSPAN attribute a cell can span more than one row, and with the COLSPAN attribute a cell can span more than one column.


2 Answers

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>
like image 181
Asons Avatar answered Oct 05 '22 23:10

Asons


I've managed to achieve the desired look using the following CSS:

  td:first-child {
    font-weight: bold;
  }
  thead + tbody td:first-child {
    font-weight: lighter;
  }
like image 40
rouan Avatar answered Oct 05 '22 23:10

rouan