Making a Bootstrap table column fit to content
I'm using Bootstrap, and drawing a table. The rightmost column has a button in it, and I want it to drop down to the minimum size it needs to fit said button.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<table class="table table-responsive">
<tbody>
<tr>
<th>Name</th>
<th>Payment Method</th>
<th></th>
</tr>
<tr>
<td>Bart Foo</td>
<td>Visa</td>
<td><a role="button" class="btn btn-default btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">View</a></td>
</tr>
</tbody>
</table>
This renders like this:
With some firebug highlighting, the column width has come out this wide:
That column scales with the page, while the page is in the larger dynamic width modes. I have some idea how I'd go about fixing this in pure CSS, but most of those approaches will probably cause issues with the low width versions of the site.
How would I make that column drop down to the width of it's contents?
(As ever - Existing bootstrap classes > pure CSS > Javascript)
Solution 1:
Make a class that will fit table cell width to content
.table td.fit,
.table th.fit {
white-space: nowrap;
width: 1%;
}
Solution 2:
Tested on Bootstrap 4.5 and 5.0
None of the solution works for me. The td
last column still takes the full width. So here's the solution works.
CSS
Add table-fit
to your table
table.table-fit {
width: auto !important;
table-layout: auto !important;
}
table.table-fit thead th, table.table-fit tfoot th {
width: auto !important;
}
table.table-fit tbody td, table.table-fit tfoot td {
width: auto !important;
}
Scss
Here's the one for scss
uses.
@mixin width {
width: auto !important;
}
table {
&.table-fit {
@include width;
table-layout: auto !important;
thead th, tfoot th {
@include width;
}
tbody td, tfoot td {
@include width;
}
}
}