Search code examples
htmlcsshtml-table

Flexible width in HTML table


I would like my table to fulfill these properties:

  • The width of the table is 100% of the parent container.
  • All columns width are fit to the maximum column width.
  • The column flex-column takes the remaining space.

enter image description here

In the figure, the middle column takes, the remaining horizontal space while the other columns width are fitted to their content.

I played with Flexbox and CSS Grid, but I couldn't get any result yet. What is the proper method?

table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}

th,
td {
  padding: 8px;
  border: 1px solid black;
}

th.flex-column,
td.flex-column {
  width: auto;
}

th:not(.flex-column),
td:not(.flex-column) {
  white-space: nowrap;
}
<table>
  <thead>
    <tr>
      <th>A</th>
      <th class="flex-column">B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="3">foo</td>
      <td class="flex-column">2</td>
      <td>3</td>
    </tr>
    <tr>
      <td class="flex-column">4</td>
      <td>5</td>
    </tr>
    <tr>
      <td class="flex-column">6</td>
      <td>7</td>
    </tr>
  </tbody>
</table>


Solution

  • Remove the table-layout: fixed, use a very small fixed value for the side colums, and possibly also use white-space: nowrap; on them if you want their content not to be wrapped. The width will not remain at that fixed value, but adapt if needed.

    table {
      width: 100%;
      border-collapse: collapse;
    }
    
    th,
    td {
      padding: 8px;
      border: 1px solid black;
    }
    
    th.flex-column,
    td.flex-column {
      text-align: left;
    }
    
    th:not(.flex-column),
    td:not(.flex-column) {
      white-space: nowrap;
      width: 6px;
    }
    <table>
      <thead>
        <tr>
          <th>A</th>
          <th class="flex-column">B</th>
          <th>C</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td rowspan="3">foo</td>
          <td class="flex-column">2</td>
          <td>3</td>
        </tr>
        <tr>
          <td class="flex-column">4</td>
          <td>5</td>
        </tr>
        <tr>
          <td class="flex-column">6</td>
          <td>7</td>
        </tr>
      </tbody>
    </table>