How to make a scrollable HTML table

There are times when scrollbars are needed in an html table. This is true in situations when a table is larger than its container. In such cases, without scrollbars, only part of the table will be visible. Take the table below for example:
scrollable table

The table has scrollbars. Without scrollbars, it looks as follows:

table no-scroll

Making a table scrollable is actually quite straightforward. It is a matter of adding scrollbars to the table’s container. That is how the above scrollbars were added. The scrollbars don’t belong to a table. They belong to a <div> which is a parent to the table.

This is how the html code looks like:

<div class="tableContainer">
<table border="1">
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
</tr>
<tr>
<td>row 3, cell 1</td>
<td>row 3, cell 2</td>
<td>row 3, cell 3</td>
<td>row 3, cell 4</td>
</tr>
<tr>
<td>row 4, cell 1</td>
<td>row 4, cell 2</td>
<td>row 4, cell 3</td>
<td>row 4, cell 4</td>
</tr>
</table>
</div>

Now, in order to make scrollbars appear, the container needs to be smaller than the table. For our example, we shall give “tableContainer” a width and height which is smaller than that of the table. We do this using the following CSS styles:

.tableContainer{
	height: 150px; 
	width:300px; 	
}
.tableContainer table{
				
	height: 250px; 
	width: 320px
}

At this point, the table displays as follows on the webpage.
table2

You’re probably wondering where the scrollbars are. Well, in order to make scrollbars appear, there is one CSS property which you need to add. It is the “overflow” property. This property determines what happens when portion of one element covers another element. In this case, the <div> covers part of the table. In order to add scrollbars, we have to give “overflow” a value of “auto”, as follows:

overflow: auto;

This rule is supposed to be added to the “tableContainer” style. This style now looks as follows:

.tableContainer{
height: 150px;
width:300px;
overflow: auto;
border: 2px solid black;
}

With this, our table now appears with scrollbars.

The above approach is great. However, in some cases, you may want to scroll the body of the table, without touching its head. To achieve this, you will need to use the HTML5 <thead> and <tbody> tags. When you want to add scroll bar to just one cell, you have to change the td width and then apply the scroll style.

Also see some more on creating HTML table here

Leave a Reply

Your email address will not be published. Required fields are marked *