HTML Table with fixed Thead and vertical scrollable Tbody — Logical implementation using CSS grid

In this post, I am going to describe how to implement HTML Table with fixed Thead and scrollable Tbody using CSS grid.

Let's first understand CSS grid layout.

CSS Grid Layout introduces a two-dimensional grid system to CSS. Grids can be used to layout major page areas or small user interface elements.

For example- We create a grid container by declaring display: grid or display: inline-grid on an element. As soon as we do this, all direct children of that element become grid items.

HTML

CSS

In the above example, All the direct children of “class=grid-layout” are now grid items.

Now let’s use the CSS grid to implement HTML Table with fixed Thead and vertical scrollable Tbody.

Example HTML code which has 5 columns and 7 data rows.

HTML

1. First style <table> element with grid-layout structure by giving it display: grid style property. Immediate child items<thead> and <tbody> will now be considered grid items.

2. Now align table immediate child items in one column using grid-template-columns: 1fr and in two rows using grid-template-rows: 1.25rem 1fr.

3. <thead> will have 1.25rem as height and <tbody> will take rest available space with in <table>.

4. Now let’s align all <th> and <td> as grid items. To do this, we need to set its immediate parent container as a grid. We will do this by applying display: grid for <tr>.

5. Now let’s divide the grid into 5 equal-width columns using grid-template-columns: repeat(5, 1fr) property. Depending on our usecase, we can give each column specific width as well using grid-template-columns: 100px 200px 300px 400px 500px.

6. Now to make tbody vertical scrollable — we need to ensure it has overflow-y property set to auto and height is set to 100% to take available table height.

CSS

Thanks for taking the time to read this post. I hope you find it helpful

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store