skip to Main Content

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.

2

Answers


  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';
      }
    });
    
    Login or Signup to reply.
  2. Increase z-index , Set a high z-index (example : 999 ) on the sticky header
    Add border-bottom , Add a border-bottom ( example : 1px solid #ddd ) to the header to create a visual separation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search