<table border="1" style="height:50px; overflow:auto;">
<thead>
<tr>
<th>Col 1
</th>
<th>Col 2
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 3
</td>
<td>Cell 4
</td>
</tr>
<tr>
<td>Cell 5
</td>
<td>Cell 6
</td>
</tr>
</tbody>
</table>
I'd like the above table to be of 50px height so the scrollers would kick in when the content grows, but I'd also like table headers (thead) to be fixed always on top, while other content can be scrollable. Is there an solution, preferable using jQuery?
Thanks in advance for your help.
To freeze the row/column we can use a simple HTML table and CSS. HTML: In HTML we can define the header row by <th> tag or we can use <td> tag also. Below example is using the <th> tag. We also put the table in DIV element to see the horizontal and vertical scrollbar by setting the overflow property of the DIV element.
By setting postion: sticky and top: 0, we can create a fixed header on a scroll in HTML tables.
Found myself in need of similar functionality. Couldn't find anything light and simple, so I created the plugin myself: TH Float jQuery Plugin
I hope someone finds it useful.
Here it is my trick. You have to change something in your html too.
The trick consists in inserting through js after the real scrolling thead, a secondary and identical thead positioned fixed. Cells widths are adjusted through js too.
Adjust the code on your needs.
CSS
thead.fixed {
position: fixed;
}
HTML
<div style="overflow: auto;">
<table id="my_table">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Body 1</td>
<td>Body 2</td>
</tr>
</tbody>
</table>
</div>
jQuery
$( function() {
fixListThead();
});
$(window).resize( function() {
fixListThead();
});
var fixListThead = function() {
$('#my_table thead.fixed').remove(); // Removes (if present) fixed thead when resizing
var widths = [];
$('#my_table thead th').each( function(i, element) {
widths[i] = $(element).width();
});
$('<thead class="fixed">' + $('#my_table thead').html() + '</thead>').insertAfter($('#my_table thead'));
$('#my_table thead.fixed th').each( function(i, element) {
$(element).css('width', widths[i] + 'px');
});
}
Try this post: jQuery Scrollable, Sortable, Filterable table
It looks like they've got what you need (which is a freezable, scrollable jquery table).
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