JSFiddle - React, Tailwind, and code Playground
HTML
<div class="fixed-table">
<div class="table-content">
<table id="myTable" class="table-fixed-header">
<thead class="header">
<tr>
<th>aakfj</th>
<th>aakfj</th>
<th>setrestaakfj</th>
<th>aakfj</th>
<th>aakfj</th>
<th>aakfj</th>
<th>aakststetfj</th>
<th>aakfj</th>
<th>aasetestkfj</th>
<th>aakfj</th>
<th>aakfj</th>
<th>aaststkfj</th>
<th>aakfj</th>
<th>aakststfj</th>
<th>aakfj</th>
<th>aakststfj</th>
</tr>
</thead>
<tbody>
<tr>
<td>aakertertertertetetfj</td>
<td>aakfj</td>
<td>setrestaakfj</td>
<td>aaketttttttttttttttdfj</td>
<td>aakfj</td>
<td>aakfj</td>
<td>aakststetfj</td>
<td>aaketttttttttteefj</td>
<td>aasetestkfj</td>
<td>aadxhhhhhhhhhhhhhhhkfj</td>
<td>aadgggggggggggggkfj</td>
<td>aaststkfj</td>
<td>aakfj</td>
<td>aakdgxxxxxxxxxxxxxgststfj</td>
<td>aakwrrwwwwwwwwwwwwwwfj</td>
<td>aaksxdhhhhhhhhhhhhhhhtstfj</td>
</tr>
</tbody>
</table>
</div>
</div>
CSS
.fixed-table .header-fixed {
position: absolute;
top: 0px;
z-index: 1020; /* 10 less than .navbar-fixed to prevent any overlap */
border-bottom: 1px solid #d5d5d5;
border-left: 1px solid #d5d5d5;
border-top: 1px solid #d5d5d5;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
.fixed-table{
display:block;
position:relative;
}
.fixed-table th{
padding: 8px;
line-height: 18px;
text-align: left;
}
.fixed-table .table-content{
display:block;
position: relative;
height: 300px; /*FIX THE HEIGHT YOU NEED*/
overflow-y: auto;
}
.fixed-table .header-copy{
position:absolute;
top:0;
left:0;
}
.fixed-table .header-copy th{
background-color:#fff;
}
JavaScript
(function($) {
$.fn.fixedHeader = function() {
return this.each(function() {
var o = $(this),
nhead = o.closest('.fixed-table');
var $head = $('thead.header', o);
$head.clone().removeClass('header').addClass('header-copy header-fixed').appendTo(nhead);
var ww = [];
o.find('thead.header > tr:first > th').each(function(i, h) {
ww.push($(h).width());
});
$.each(ww, function(i, w) {
nhead.find('thead.header > tr > th:eq(' + i + '), thead.header-copy > tr > th:eq(' + i + ')').css({
width: w
});
});
nhead.find('thead.header-copy').css({
margin: '0 auto',
width: o.width()
});
/*
//makes the header scroll horizontally with the table if
// the table is too wide to fit into the surrounding div
o.closest('.table-content').scroll(function(){
var scroll = $(this).scrollLeft();
nhead.find('thead.header-copy').css('margin-left', -scroll);
}); */
});
};
$(".table-content").scroll(function(){
var $this = $(this),
$header = $(".header-fixed");
$header.css("margin-left", 0 - $this.scrollLeft() )
});
})(jQuery);
window.onload = function() {
// add 30 more rows to the table
var row = $('table#myTable > tbody > tr:first');
for (i = 0; i < 30; i++) {
$('table#myTable > tbody').append(row.clone());
}
$('.table-fixed-header').fixedHeader();
$('.fixed-table').on('click', '.header-fixed th', function(){
var th=$(this).index();
alert('Column number is : ' + th + ' and text is : ' + $(this).text());
});
}