There is a trick that involves setting some cells to a very small width, and then applying a white-space: nowrap
property:
<table>
<tr>
<td class="min">id</td>
<td class="min">tiny</td>
<td>Fills space</td>
<td>Fills space</td>
<td class="min">123</td>
<td class="min">small</td>
<td>Fills space, wider</td>
<td>Fills space</td>
<td class="min">thin</td>
</tr>
</table>
td {
width: auto;
}
td.min {
width: 1%;
white-space: nowrap;
}
Live demo
As you can also see in the above fiddle, nowrap
forces the table cell to prevent any line-breaks, and thus align its width to the smallest possible.
NOTE: If you have a thead
, you want to apply the td
's stylings to th
as well.
UPDATE #1: Ellipsis (...)
To automatically collapse a longer column into ellipses, the text-overflow: ellipsis
is what you are likely looking for:
td.cell-collapse {
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
}
Live demo
This also requires overflow
set to hidden
, as well as a width
or max-width
with a fixed value. Add the cell-collapse
class to cells whose width you would like to limit.
UPDATE #2: Handling Bootstrap
Bootstrap's table
class sets width: 100%;
which will mess up this approach. You can fix that with table { width: inherit !important; }
Live demo
NOTE: The tables in this approach already have full width because table cells already have width: auto;
.
Previous Javascript-base solution removed, since the pure CSS-based approach now works consistently across all modern browsers. The original code is still available at the linked JSfiddle, commented out.