Search code examples
htmlhtml-table

can the second thead row define the layout in a fixed table?


I'm working with a table that has the table-layout: fixed property as illustrated in the example below :

<table border="1" style="table-layout: fixed; width: 100%">
    <thead>
        <tr>
            <td colspan="4" style="width:100%"> Hello there !</td>
        </tr>
        <tr>
            <td style="width:20%">I</td>
            <td style="width:30%">AM</td>
            <td style="width:15%">STUCK</td>
            <td style="width:35%">!!!</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td></td>
            <td colspan="2">E</td>
            <td></td>
        </tr>
    </tfoot>
</table>

As you can see if you run the snippet, the width property is ignored due to the fact that the layout is defined by the first row in thead.

If it is removed, the issue gets resolved as demonstrated below :

<table border="1" style="table-layout: fixed; width: 100%">
    <thead>
        <tr>
            <td style="width:20%">I</td>
            <td style="width:30%">AM</td>
            <td style="width:15%">STUCK</td>
            <td style="width:35%">!!!</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td></td>
            <td colspan="2">E</td>
            <td></td>
        </tr>
    </tfoot>
</table>

Is there a way to make have a table head first row not define the layout ?


Solution

  • Add colgroup after your table tag. Define width and number of columns here

    <table border="1" style="table-layout: fixed; width: 100%">
      <colgroup>
        <col span="1" style="width: 20%;">
        <col span="1" style="width: 30%;">
        <col span="1" style="width: 15%;">
        <col span="1" style="width: 35%;">
      </colgroup>
      <thead>
        <tr>
          <td colspan="4"> Hello there !</td>
        </tr>
        <tr>
          <th>I</th>
          <th>AM</th>
          <th>STUCK</th>
          <th>!!!</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>A</td>
          <td>B</td>
          <td>C</td>
          <td>D</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td></td>
          <td colspan="2">E</td>
          <td></td>
        </tr>
      </tfoot>
    </table>