Make HTML Table Scrollable

This article will introduce a method to make a vertically scrollable HTML table.

Set the CSS overflow-y Property to scroll to Make HTML Table Scrollable

When an HTML table is lengthy, a feature to scroll only the table, not the entire page, is needed. To achieve this functionality, we can use the overflow-y property.

Here, y represents the y axis. The property defines the overflow property of a block-level element along the vertical axis.

The scroll value makes the block-level element scrollable from top to bottom.

To make an HTML table vertically scrollable, we can wrap the table with a <div>. Then, we can set a fixed height for the <div> using the height property.

After that, we can set the overflow-y property to scroll. If the table height exceeds the height of the div we had set, then the overflow-y: scroll will make the table scrollable in the y-direction (vertically).

Therefore, we need to ensure that the height of the table exceeds the height of the <div>.

For example, create a div and give it a class name of container. Inside that div, create a table and give it a class name of data.

Fill the table with data using tr, th, and td tags.

In CSS, select the container class and set its height property to 70px and its overflow-y property to scroll. Ensure the table contents have a height of more than 70px.

Next, select the table using the class selector and the table’s th and td elements. Then, set its border property to 1px solid black, border-collapse property to collapse and padding to 4px. (Note: This is not compulsory, this is to make the table more readable.)

The example below shows that the table is vertically scrollable, as the height of the table is more than that of the div or .container.

Example Code:

<div class="container">
<table class="data">
<tr>
 <th>id</th>
 <th>Name</th>
 <th>Country</th>
</tr>
<tr>
 <td>1</td>
 <td>John Doe</td>
 <td>Nepal</td>
</tr>
<tr>
 <td>2</td>
 <td>Sam Smith</td>
 <td>India</td>
</tr>
<tr>
 <td>3</td>
 <td>Jack Daniels</td>
 <td>China</td>
</tr>
</table>
</div>
.container {
 height: 70px;
 overflow-y: scroll;
}
.data, th, td {
 border: 1px solid black;
 border-collapse: collapse;
 padding: 4px;
}

As a result, the whole table is not visible as we load the page. It is because we have set 70px as the height of the container.

But when we scroll down vertically, we can see the rest of the table contents.

This way, we can make the HTML table vertically scrollable using the overflow-y property and setting it to scroll.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - HTML Table

  • Center a Table in HTML
  • Add Image Inside Table Cell in HTML
  • Align Table to Top in HTML
  • Related Article - HTML Scroll

  • Center a Table in HTML
  • Add Image Inside Table Cell in HTML
  • Align Table to Top in HTML