How to set tbody height with overflow scroll
To quickly answer the question, if you need a tbody that has a max-height and scrolls vertically, try doing this:
But wait, we aren't done yet! Keep thead on top:
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:
This takes care of equal distribution of cell widths. Also, assign desirable width to cells in th and td:
Sticky headers: Keep 'em stuck
Sticky headers are cool but they can be slippery! Using position:sticky helps keep them in place:
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:
(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!
Was this article helpful?