I have a simple HTML table with table-layout
set to auto
. This table has some regular data columns and at last a special action column, i.e. a column with some buttons inside.
I now want my table to simply divide up the available space to all columns equally EXCEPT for the last column. I want this action column to take up the least available space required, all remaining space can just be divided equally among the remaining tables.
But I have not been able to achieve this. I cannot work with a fixed with for this action column, the number of buttons is unknown upfront. I just need it to make it take the least available automatically, not by defining an explicit width.
Below is a minimal reproducible example. It has 4 columns (3+1). The desired result is that the last one should be as small as possible.
table {
width: 100%;
table-layout: auto;
/* wether it be 'auto' or 'fixed', last column should not be larger than necessary */
}
tr {
text-align: left;
}
th:last-of-type {
max-width: max-content;
background-color: orange;
}
td:last-of-type {
background-color: yellow;
max-width: max-content;
/* Does not work */
}
<table>
<tr>
<th> Header 1 </th>
<th> Header 2 </th>
<th> Header 3 </th>
<th> Actions </th>
</tr>
<tr>
<td> Data1_1 </td>
<td> Data1_2 </td>
<td> Data1_3 </td>
<td>
<button>Button 1</button>
</td>
</tr>
<tr>
<td> Data2_1 </td>
<td> Data2_2 </td>
<td> Data2_3 </td>
<td>
<button>Button 1 </button>
<button>Button 2</button>
</td>
</tr>
</table>
2
Answers
CSS-Grid/
subgrid
can do that rather than a table.Keeping essentially the same structure but swapping out for
div
andspan
elements.One way to achieve your required functionality is by setting the width of the last column so that it occupy only that space. **
Changes Made: I just assigned the last column in first row a specific width of 25%.
If you still have any queries. Feel free to comment down on this post