TheRogerLAB Codes

Create a fixed table header

  Feb, 2022

Introduction

If you have a table with many rows, you will need to scroll down and up, causing that headers move along with the rows. In some scenarios is preferable to have the header visible all the time while scrolling, so you need to let the header static. You can achieve this using CSS:

HTML Code

<div class="tableContainer">
  <table>
    <thead>
    <tr class="headers">
      <th>Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Age</th>
    </tr>
    </thead>
    <tbody>
      <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@gmail.com</td>
      <td>23</td>
    </tr>
    </tbody>    
  </table>
</div>

CSS Code

body{
  font-size:23px;
}
table, th, td {
  border:1px solid gray;
  border-top:none;
  border-collapse: collapse;
  text-align:left;
}
table{
  width:100%;
}

.tableContainer{
  height:200px;  
  overflow:auto;
  border:1px solid gray;
}
.headers{
  position: sticky;
  top: 0px;
  background-color:#b3b3b3;
}


Check a working demo for this code:

SEE DEMO RATE THIS ARTICLE
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com