Html table with 100% width, with vertical scroll inside tbody
The purpose here is to give our table
a 100% width, keep the headers and footers in place, and make the body vertically scrollable. This calls for some CSS magic on tbody
, thead
, and tfoot
. Below is simplified CSS that does just that:
Voila! A full-width table with scrollable tbody
is ready, and headers and footers are kept intact.
Perfecting column alignment
By defining display: block;
for tbody
, maintaining thead
and tbody
column alignment can be a tricky task. Here's where the fluid layout steps in. Use %
for column widths and align thead
and tbody
columns dynamically. CSS calc()
function can be your friend to accommodate the vertical scrollbar:
Keep in mind, scrollbar widths can differ across browsers, so it's a good idea to test how your table performs in each one of them. It's like an audition for browsers where you're the cutthroat judge. IE11 attendees may require JavaScript chaperones to handle this nerve-wracking audition.
Keeping table headers on top
Locking the position of our thead
to the top while the tbody
ferociously scrolls is the next task on our list. Use position: sticky;
and top: 0;
right here:
Accompanied by the rule above, our headers will sit back, sip some tea, and watch the body content scroll by. They deserve it after carrying all those column names.
Remember to make th
and td
elements padding keep in harmony, just like a lovely couple waltzing around the dance floor.
The cross-browser performance race
Browsers play a key role in formatting the scrollable tbody
. Some contestants like JavaScript plugins might seem gaudy at first, but they promise a full-fledged and reliable solution. They can get a bit loud sometimes, so if you're a minimalist, go for the lean solution like the one discussed here.
If you foresee a surge of lengthy content in your table cells, it's time to play white-space: nowrap;
get-out-of-jail-free card to prevent your layout from pandemonium.
Designing for all screens and users
The table with scrollable tbody
needs to look its best on all screens. Consider horizontal scrolling or stacking cells vertically for smaller screens. Modify your tailor-made CSS for responsive tables:
Designing for everyone also means considering accessibility. Ensure you use relevant scope attributes (scope="col"
or scope="row"
) for headers and provide appropriate text alternatives for screen readers.
Exploring further frontiers
Sometimes basic table functions are not enough. One may need advanced features like sorting and filtering. Plugins and libraries like React Table come into the picture to extend basic HTML tables. Your JavaScript skills can also shine here for creating custom solutions to enhance table functionalities. After all, if you got it, flaunt it!
Was this article helpful?