Search code examples
htmlhtml-table

Setting a Html table 'tr' width to have a different width for each cell on one row


I have the following table declaration:

<table width="80%" style="border: 1px solid black; border-collapse: collapse; table-layout: fixed;">
<tbody>
<tr>
<td style="border: 1px solid black; border-collapse: collapse;" width="80%" colspan="2" >This is a very long first line here, taking the entire width of the table</td>
</tr>
<tr>
<td style="border: 1px solid black;" width="10%">Comment</td>
<td style="border: 1px solid black;" width="80%">My text on the comment cell</td>
</tr>
</tbody>
</table>

I don't understand why my second column is as wide as the first one. I thought that by specifying the table-layout: fixed; property for the table, and setting the columns widths, I would obtain what I wanted, which was:

  • A first row with only one cell of a width which would be 100% of the table width
  • A second row with a small first cell, and a second wide second cell

Solution

  • table-layout: fixed allows you to set the widths of each <th> or the first row of <td> within the <tbody> if there's no <thead>. Once the widths are established, each column will conform to those widths. It's the nature of a column. If you want different widths for each row try colspan.

    table {
      table-layout: fixed;
      border-collapse: collapse;
      width: 100%;
    }
    
    table,
    th,
    td {
      border: 3px solid black;
    }
    
    th {
      width: 25%
    }
    <table>
      <thead>
        <tr>
          <th>I</th>
          <th>II</th>
          <th>III</th>
          <th>IV</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td colspan='4'>colspan="4"</td>
        </tr>
        <tr>
          <td></td>
          <td colspan='3'>colspan="3"</td>
        </tr>
        <tr>
          <td colspan='2'>colspan="2"</td>
          <td colspan='2'>colspan="2"</td>
        </tr>
      </tbody>
    </table>