I’ve been reading several articles and questions related to the table-layout property on Stack Overflow, but I haven’t found a solution that addresses my specific issue. I’ve been stuck on this problem for a few hours, so I’m hoping someone can guide me in the right direction.
I have a table that handles a large amount of data and is usually much wider than the container. To allow horizontal scrolling, I’ve set the container to overflow-x: scroll. The client has the ability to define the widths of each column. However, a new requirement has emerged: the client wants the table to automatically adjust the column widths to the minimum necessary if a width is not explicitly defined.
I’ve come across suggestions in various posts that recommend leaving the last column to have an automatic width. However, in my case, I need the flexibility to set any column to have an auto width.
I’ve considered changing the table-layout property to auto, as I believe it might be the solution. However, when I make this change, I’m unable to set the width of any column individually; instead, the widths adjust equally for all columns.
Here’s a small snippet that illustrates the issue. The column with ### should have an auto width, but currently, it gets hidden behind col 4 when I attempt to do so.
.container {
width: 400px;
border: 1px solid red;
overflow-x: scroll;
}
.container table {
width: 100%;
table-layout: fixed;
text-align: left;
border-collapse: collapse;
}
.container th,
.container td {
border: 1px solid blue;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
<div class="container">
<table>
<colgroup>
<col style="width: 50px;">
<col style="width: 300px;">
<!-- <col style="width: 50px;"> -->
<col style="width: auto;">
<col style="width: 100px;">
</colgroup>
<thead>
<tr>
<th>Columna 1</th>
<th>Columna 2</th>
<th>###</th>
<th>Columna 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Contenido 1</td>
<td>Contenido 2</td>
<td>###</td>
<td>Contenido 4</td>
</tr>
<tr>
<td>Contenido 5</td>
<td>Contenido 6</td>
<td>###</td>
<td>Contenido 8</td>
</tr>
</tbody>
</table>
</div>
2
Answers
So all you need to do is changing the required columns width to auto
<col style="auto;">
and adding a class to ### elements<td class="hash">###</td>
and as by CSS side you need to change the CSS code to:So it will hide all other fields but those that contains hash class
Solution
table-layout: auto;
– correct direction of thoughts. And in order to set a specific width for the cells, set them simultaneouslymin-width
andmax-width
: