Creating an HTML table with fixed headers in 2 steps

It is easy to develop a pure HTML table with fixed headers.

Sarthak Aggarwal
Level Up Coding

--

Photo by Abel Y Costa on Unsplash

We are going to use position: sticky CSS property to allow headers of the table to give an illusion of fixed headers.

According to MDN web docs:

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

Steps to follow

We are going to use React for demo purposes.

There are 2 main steps in creating an HTML table with fixed headers:

#1 Create an HTML Table

Create an HTML table and wrap it in the parent div.

The parent div will be used to adjust the table height and its overflow property.

index.js

#2 Define CSS property and add position: sticky to th of the table

The position: sticky will help to provide an illusion of fixed headers.

styles.css

Final Result

The headers of the HTML table stick to the top of the parent div while scrolling.

I wish you a happy HTML table.

--

--