JSFiddle - React, Tailwind, and code Playground
by TicoRicoRay
HTML
<div class='ux-data-table'>
<div class='ux-data-table-inner'>
<table>
<colgroup>
<col span="1" style="color:blue;"/>
<col span="1" style="width:20px;"/>
<col span="1" style="width:20px;"/>
<col span="1" style="width:20px;"/>
</colgroup>
<thead>
<tr>
<th>#</th>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Item 1</td>
<td>CD player</td>
<td>Used</td>
<td>Sony</td>
</tr>
<tr>
<td>2</td>
<td>Item 2</td>
<td>Variscope</td>
<td>Used</td>
<td>General</td>
</tr>
<tr>
<td>3</td>
<td>Item 3</td>
<td>Microphone</td>
<td>New</td>
<td>Mastersound</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
<td>4</td>
<td>Item 4</td>
<td>Cable</td>
<td>New</td>
<td>Techable</td>
</tr>
<tr>
...
CSS
.ux-data-table {
width: 100%;
height: 200px;
overflow: auto;
}
/* Prevents the header from overflowing the scrollbars */
.ux-data-table-inner {
position: relative;
}
.ux-data-table table {
width: 100%;
}
.ux-data-table table,
.ux-data-table th,
.ux-data-table td {
background-color: red;
color: white;
border: 1px solid black;
width: 400px;
min-width: 400px;
}
.ux-data-table thead {
position: absolute;
}
.ux-data-table tbody {
margin-top: 20px;
display:block;
}
.ux-data-table td {
background-color: white;
color: red;
border: 1px solid black;
}
JavaScript
document.querySelector('.ux-data-table').onscroll = function (e) {
// called when the window is scrolled.
var topOfDiv = Math.max(document.querySelector(".ux-data-table").scrollTop - 2, 0);
document.getElementsByTagName('thead')[0].style = "top:" + topOfDiv + "px;";
}