Categories
JavaScript Answers

How to Let an HTML Table’s Body Scroll but Keep the Header Fixed in Place?

Spread the love

Sometimes, we want to add an HTML table that has a scrollable body but with the header fixed in place.

In this article, we’ll look at how to add a table where the table body scrolls but the table header stays in place.

Create a Table That Has a Fixed Header

We can create an HTML table that has a fixed header with some CSS.

For instance, if we have the following table:

<table>
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
  </tbody>
</table>

Then we can style it by writing the following CSS:

table {
  overflow: scroll;
  display: block;
  height: 120px;
}

thead>tr {
  position: absolute;
  display: block;
  padding: 0;
  margin: 0;
  top: 0;
  background-color: white;
}

tbody>tr:nth-of-type(1) {
  margin-top: 16px;
}

tbody tr {
  display: block;
}

td,
th {
  width: 70px;
  border-style: solid;
  border-width: 1px;
  border-color: black;
}

We set the height of the table element to 120px to make restrict the height of it so we can make it scrollable.

To make it scrollable, we set the overflow CSS property to scroll .

Then we set the tr elements in the thead to absolute position so they stay in place.

Also, we set the tr elements in thead to a white background so that the elements below will be hidden when we scroll them.

Conclusion

We can make an HTML table with a scrollable body and a fixed header with some CSS styles.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *