I have a html table with a sticky header. I need to fix it because in Chrome the top of column values can be seen above the header:
Top of table header
<div style="max-height: 700px; overflow-y: auto;">
<table class="table table-sm table-striped table-hover">
<caption hidden></caption>
<thead style="position: sticky; top: 0; background-color: white; z-index: 100;">
<tr class="table-header">
<th style="width: 5%"></th>
<th style="width: 10%;text-align: center; vertical-align: middle">
STUFF 1
</th>
<th style="width: 10%;text-align: center; vertical-align: middle">
STUFF 2
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td>
<input type="checkbox">
</td>
<td style="text-align: center; vertical-align: middle">text</td>
<td style="text-align: center; vertical-align: middle">text</td>
</tr>
</tbody>
</table>
</div>
I tried modifying z-index, the height and padding of the header, using grid.
1
If CSS isn’t enough to handle this issue across all browsers, a JavaScript solution might be necessary. You can use a small script to manually control the positioning of the header
window.addEventListener('scroll', function() {
const tableHeader = document.querySelector('thead');
const tableHeaderOffset = tableHeader.getBoundingClientRect().top;
if (tableHeaderOffset <= 0) {
tableHeader.style.position = 'fixed';
tableHeader.style.top = '0';
tableHeader.style.zIndex = '100';
} else {
tableHeader.style.position = 'sticky';
tableHeader.style.top = '0';
}
});
1
The issue with the sticky header in Chrome is likely due to improper stacking context or insufficient height. Adjusting the z-index ensures the header stays on top, and adding padding prevents content from overlapping.
I have had the same issue here but got it fixed.
Simply adjust the ‘z-index’ and add padding to the ‘th’ elements.