Position sticky for complex table header

In this article, you can learn, how to fix the table header when scrolling the page.

CSS:

table {
  border: 1px solid black;
  font-size: 14px;
  margin: 10px 0;
  position: relative;
}

thead tr th {
  background-color: gray;
  position: sticky;
  top: -2px;
}

thead {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
}

td {
  border: 1px solid black;
  line-height: 1.25;
  overflow: hidden;
  padding: 4px;
}

 

HTML sample table structure:

<table class='sticky-table'>
  <thead>
    <tr>
      <th rowspan="2">First column</th>
      <th colspan="3">Top of second column</th>
    </tr>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
    <tr>
      <td>First cell</td>
      <td>Second cell</td>
      <td>Third cell</td>
      <td>Fourth cell</td>
    </tr>
  </tbody>
</table>

 

Using javascript to control table header

 

try{
var tableHeaderTop = document.querySelector('.sticky-table thead').getBoundingClientRect().top;
var ths = document.querySelectorAll('.sticky-table thead th')

for(var i = 0; i < ths.length; i++) {
  var th = ths[i];
  th.style.top = th.getBoundingClientRect().top - tableHeaderTop + "px";
}
}
catch(){
}

Related Post

Maksud

Maksud

I am a thinker, not a talker.