JSFiddle - React, Tailwind, and code Playground
by Newton Anbarasu
HTML
<div class="table-container">
<table id="scrollable-table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
<!-- Add more header columns if needed -->
</tr>
</thead>
<tbody>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
<tr>
<td>test</td>
<td>12</td>
<td>bangalore</td>
<td>test</td>
<td>12</td>
<td>bangalore</td>
</tr>
</tbody>
</table>
</div>
CSS
.table-container {
width: 100%;
overflow-x: auto;
}
#scrollable-table {
border-collapse: collapse;
width: auto;
}
#scrollable-table th,
#scrollable-table td {
border: 1px solid #ddd;
padding: 8px;
min-width: 100px;
/* Adjust the width as needed */
}
#scrollable-table th:first-child,
#scrollable-table td:first-child {
position: sticky;
left: 0;
background-color: #fff;
z-index: 1;
/* Ensure the first column is above other columns */
}
#scrollable-table th:nth-child(2),
#scrollable-table td:nth-child(2) {
position: sticky;
left: 100px;
/* Width of the first column */
background-color: #fff;
z-index: 1;
/* Ensure the second column is above other columns */
}
JavaScript
$(document).ready(function() {
$('.table-container').scroll(function(e) {
var scrollTop = $(this).scrollTop();
var scrollLeft = $(this).scrollLeft();
$('th:first-child, td:first-child', '#scrollable-table').css({
'transform': 'translateY(' + scrollTop + 'px)'
});
$('th:nth-child(2), td:nth-child(2)', '#scrollable-table').css({
'transform': 'translateY(' + scrollTop + 'px) translateX(' + scrollLeft + 'px)'
});
});
});