Horizontal Scrollbar for Tables
To display horizontal scrollbar for tables using CSS, enclose the table in a div, and set the div’s CSS property overflow-x
to auto
;
The HTML code to enclose a table in a div is shown in the following.
</>
Copy
<div id="tablediv">
<table>
<!-- table content -->
</table>
</div>
The CSS code to set the overflow-x
property for the enclosing div is
</>
Copy
#tablediv {
overflow-x: auto;
}
Examples
1. Horizontal Scrollbar for Table
In the following example, we take a table with five columns, and width set to 1500px. If this width is greater than the allowed width for the enclosing div on your screen, then the enclosing div allows the table to overflow in x-axis direction, enabling the horizontal scrollbar.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
width: 1000px;
}
#tablediv {
overflow-x: auto;
}
th {
text-align: left;
padding: 0.5em 0;
background-color: #adf;
}
tr:nth-child(odd) {
background-color: #eee;
}
</style>
</head>
<body>
<div id="tablediv">
<table>
<thead>
<tr>
<th>Fruit</th>
<th>Quantity 1</th>
<th>Quantity 2</th>
<th>Quantity 3</th>
<th>Quantity 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>32</td>
<td>22</td>
<td>55</td>
<td>88</td>
</tr>
<tr>
<td>Banana</td>
<td>48</td>
<td>23</td>
<td>84</td>
<td>11</td>
</tr>
<tr>
<td>Cherry</td>
<td>75</td>
<td>0</td>
<td>6</td>
<td>2</td>
</tr>
<tr>
<td>Mango</td>
<td>69</td>
<td>523</td>
<td>93522</td>
<td>77</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Conclusion
In this CSS Tutorial, we learned how to enable horizontal scrollbar when the width of the table is more than what we want, with examples.