DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Making Tables Scrollable in CSS

Because HTML tables are set to display: table by default, adding scrollbars to them is a bit nonintuitive.

We can set our tables to display: block and modify their overflow from there, but I've found wrapping tables in containers to be more adaptable and flexible.

Vertical table scrollbars

First, let's set up vertical scrolling.

Consider the following <table>, which is wrapped in a <div> container:

<div class="tableContainer">
    <table class="table">
        ...
    </table>
</div>
Enter fullscreen mode Exit fullscreen mode

We can set a height for the table's container and modify the table such that it will fit snug within the container:

.tableContainer {
    height: 300px;
    overflow: hidden;
}
.table {
    position: sticky;
    top: 0;
    width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

In this example, I set the height to 300px - but you can set it to whatever you want!

Our table will now have an inset vertical scrollbar and will expand no further than the height we set.

Horizontal table scrollbars

If you want to implement horizontal scrolling, there is an approach very similar to the vertical scrolling example:

.tableContainer {
    overflow: hidden;
    width: 800px;
}
.table {
    position: sticky;
    top: 0;
    width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

I set the width here to 800px, but again, you can change it to whatever you want.

If you want both horizontal and vertical scrollbars for your table, simply specify both a height and a width in .tableContainer.

Conclusion

And that's how you can make your tables scrollable with just a bit of CSS!

I refer back to this snippet all the time, and I hope you found it useful too.

Top comments (0)