fixed width table with tbody scroll
fixed width table with tbody scroll
by badsyntax
HTML
<div class="container">
<table>
<thead>
<tr>
<th class="one">Head 1</th>
<th class="two">Head 2</th>
<th class="three">Head 3</th>
<th class="four">Head 4</th>
<th class="five">Head 5</th>
<th class="six">Head 6</th>
<th class="seven">Head 7</th>
</tr>
</thead>
<tbody>
<tr>
<td class="one">Content 1</td>
<td class="two">Content 2</td>
<td class="three">Content 3</td>
<td class="four">Content 4</td>
<td class="five">Content 5</td>
<td class="six">Content 6</td>
<td class="seven">Content 7</td>
</tr>
<tr>
<td class="one">Content 1</td>
<td class="two">Content 2</td>
<td class="three">Content 3</td>
<td class="four">Content 4</td>
<td class="five">Content 5</td>
<td class="six">Content 6</td>
<td class="seven">Content 7</td>
</tr>
<tr>
<td class="one">Content 1</td>
<td class="two">Content 2</td>
<td class="three">Content 3</td>
<td class="four">Content 4</td>
<td class="five">Content 5</td>
<td class="six">Content 6</td>
<td class="seven">Content 7</td>
</tr>
<tr>
<td class="one">Content 1</td>
<td class="two">Content 2</td>
<td class="three">Content 3</td>
<td class="four">Content 4</td>
<td class="five">Content 5</td>
<td class="six">Content 6</td>
<td class="seven">Content 7</td>
</tr>
<tr>
<td class="one">Content 1</td>
<td class="two">Content 2</td>
<td class="three">Content 3</td>
<td class="four">Content 4</td>
<td class="five">Content 5</td>
<td class="six">Content 6</td>
...
CSS
table {
border-spacing: 0;
table-layout: fixed;
}
tbody,
thead {
display: block;
}
tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
width: 200px;
}
tr {
white-space: nowrap;
}
th, td {
text-align: left;
border: 1px solid red;
}
td:last-child {
margin-right: 12px;
}
.container {
width: 200px;
overflow-x: scroll;
overflow-y: hidden;
}
.one, .two, .three, .four, .five, .six, .seven {
width: 70px;
display: inline-block;
}
JavaScript
var container = $('.container');
var tbody = $('tbody');
var table = $('table');
var scrollbarWidth = 12;
var containerWidth = container.width();
var tableWidth = table.width();
container.on('scroll', function() {
tbody.width(function() {
var width = containerWidth + container.scrollLeft();
return width >= tableWidth ? 'auto' : width;
});
});