I am using DataTables and Bootstrap but always seeing a tiny bit of x-overflow on my tables, no matter how many or few columns I have. Screenshot:
My markup:
<div class="table-responsive">
<table class="table data-table">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
</div>
I don't apply any styles to the data-table
class and the table
and table-responsive
classes are both Bootstrap's.
My initialization code:
$('.data-table').DataTable();
How can I eliminate this unnecessary x-scroll? I want it only to be used when the screen is much smaller and the columns obviously do not fit.
You need to use a container. Wrap your markup in a div
with class container
or container-fluid
.
<div class="container-fluid">
<div class="table-responsive">
<table class="table data-table">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
</div>
</div>
Also add the following CSS rule:
.table-responsive {
overflow-x: inherit;
}
See this jsFiddle for code and demonstration.
The x-scroll
occurs due to the .table-responsive
class with combination of the DataTables plugin
The .table-responsive
class needs be at the parent element of the table. This is true when looking at the HTML part but it is not true after the plugin has initialized, since DataTables adds a lot of additional markup.
A workaround for this is to omit the .table-responsive
class in your HTML and add it using jQuery after the plugin has initialized.
HTML:
<div class="container-fluid">
<table id="example" class="table" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
...
</table>
</div>
JavaScript:
$(document).ready(function () {
var table = $('#example').DataTable();
$('#example').parent().addClass('table-responsive');
});
Here is a jsfiddle. Many thanks to @Gyrocode.com for providing the original jsfiddle in his answer here!
Forget Bootstrap and use the DataTables' property, scrollX set to 100%.
See it in use here: https://datatables.net/examples/basic_init/scroll_x.html
The one caveat I've found is that the table must be visible on page load. If it's not, the thead
element will be misaligned with the tbody
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With