JSFiddle - React, Tailwind, and code Playground
HTML
<table id='header-fixed'>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>third</th>
<th>fourth</th>
<th>fifth</th>
<th>sixth</th>
<th>seventh</th>
<th>eighth</th>
<th>ninth</th>
<th>tenth</th>
</tr>
</thead>
<tbody>
<tr>
<td>1111111111111111111</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>66666666666666</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
...
CSS
body {
height: 2000px;
width: 2000px;
}
table {
background: #FFF;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
}
JavaScript
//Custom JQuery Plugin
(function ($) {
$.fn.fixHeader = function () {
return this.each(function () {
var $table = $(this);
var $sp = $table.scrollParent();
var tableOffset = $table.position().top;
var $tableFixed = $("<table />")
.prop('class', $table.prop('class'))
.css({
position: "fixed",
"table-layout": "fixed",
display: "none",
"margin-top": "0px"
});
$table.before($tableFixed);
$tableFixed.append($table.find("thead").clone());
$sp.bind("scroll", function () {
var offset = $(this).scrollTop();
if (offset > tableOffset && $tableFixed.is(":hidden")) {
$tableFixed.show();
var p = $table.position();
var offset = $sp.offset();
//Set the left and width to match the source table and the top to match the scroll parent
$tableFixed.css({
left: p.left - $sp.scrollLeft() + "px",
top: (offset ? offset.top : 0) + "px",
}).width($table.width());
//Set the width of each column to match the source table
$.each($table.find('th, td'), function (i, th) {
$($tableFixed.find('th, td')[i]).width($(th).width());
});
} else if (offset <= tableOffset && !$tableFixed.is(":hidden")) {
$tableFixed.hide();
} else if (!$tableFixed.is(":hidden")) {
var p = $table.position();
$tableFixed.css({
left: (p.left - $sp.scrollLeft()) + "px"
});
}
});
});
};
})(jQuery);
$(document).ready(function () {
...