Making a Bootstrap table column fit to content
Make a class that will fit table cell width to content
.table td.fit,
.table th.fit {
white-space: nowrap;
width: 1%;
}
Add w-auto native bootstrap 4 class to the table element and your table will fit its content.
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;
}
}
}
Kind of an old question, but I arrived here looking for this. I wanted the table to be as small as possible, fitting to its contents. The solution was to simply set the table width to an arbitrary small number (1px for example). I even created a CSS class to handle it:
.table-fit {
width: 1px;
}
And use it like so:
<table class="table table-fit">
Example: JSFiddle
Bootstrap 4 example with adjusted CSS
.table-fit {
width: 1px!important;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
<h3>Regular Table</h3>
<table class="table table-bordered">
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
</table>
<h3>Compact Table</h3>
<table class="table table-bordered table-fit">
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
</table>