Making Tables Scrollable in CSS

- 2 minutes read

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.

Link to this section 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>

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%;
}

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.

Link to this section 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%;
}

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.

Link to this section 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.