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.
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>
3
Answers
Remove the
table-layout: fixed
, use a very small fixed value for the side colums, and possibly also usewhite-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.Making the flex column width 100% will work.
This snippet wraps the table in a div to demonstrate that the table can pick up the width of the parent.