Explain Codes LogoExplain Codes Logo

How to set tbody height with overflow scroll

html
responsive-design
css
table-layout
Anton ShumikhinbyAnton Shumikhin·Jan 2, 2025
TLDR

To quickly answer the question, if you need a tbody that has a max-height and scrolls vertically, try doing this:

tbody { display: block; /* Gas, meet tank. We wanna go vertical! */ max-height: 400px; /* As high as an elephant's eye! (feel free to change this) */ overflow-y: scroll; /* Let the games begin */ }

But wait, we aren't done yet! Keep thead on top:

thead { display: table; /* Let's keep things tidy */ width: 100%; /* Full throttle! */ position: sticky; /* Stay on top */ top: 0; /* Even when scrolling */ }

There you have it, the quick version of your solution. Remember, adjust as necessary for your specific layout!

Creating the scrollable tbody: step-by-step

Now, let's deepen our understanding and see how these properties and values work together, step-by-step.

Distributing cell widths evenly

To ensure that cell widths are evenly distributed, use table-layout:fixed style:

table { width: 100%; /* Grab all available space */ table-layout: fixed; /* Keep columns in line! */ }

This takes care of equal distribution of cell widths. Also, assign desirable width to cells in th and td:

th, td { width: 200px; /* Change based on your taste */ }

Sticky headers: Keep 'em stuck

Sticky headers are cool but they can be slippery! Using position:sticky helps keep them in place:

thead { position: sticky; top: 0; /* Like sticking with super glue at the top */ }

Remember to apply a similar background to thead and tbody. That way, your table structure would be less confusing while scrolling.

Handling the scrollbar width

Your thead cells may dance out of line due to the scrollbar. Adjust their width:

thead { display: table; /* Looks like a job for TABLE man */ width: calc(100% - 17px); /* Gotcha pesky scrollbar! */ }

(Change 17px according to the browser-specific scrollbar's width. Hint: some good ol' JS might help!)

Potpourri: Grids, JavaScript and Future of CSS

Sometimes display: block on tbody might mess with cell alignment. In such cases, consider a CSS grid layout or JavaScript to maintain alignment.

And keep an eye on the overflow: overlay CSS property. It might just be the future of scrolling content in containers!