How to add a scrollbar to an HTML5 table?
Instead of assuming as fixed width columns.
CSS
table.tableSection {
display: table;
width: 100%;
}
table.tableSection thead,
table.tableSection tbody {
width: 100%;
}
table.tableSection thead {
overflow-y: scroll;
display: table;
table-layout: fixed;
width: calc(100% - 16px); /* assuming scrollbar width as 16px */
}
table.tableSection tbody {
overflow: auto;
height: 150px;
display: block;
}
table.tableSection tr {
width: 100%;
text-align: left;
display: table;
table-layout: fixed;
}
Working Fiddle
If you have heading to your table columns and you don't want to scroll those headings then this solution could help you:
This solution needs thead
and tbody
tags inside table
element.
table.tableSection {
display: table;
width: 100%;
}
table.tableSection thead, table.tableSection tbody {
float: left;
width: 100%;
}
table.tableSection tbody {
overflow: auto;
height: 150px;
}
table.tableSection tr {
width: 100%;
display: table;
text-align: left;
}
table.tableSection th, table.tableSection td {
width: 33%;
}
Working fiddle
With comments
Note: If you are sure that the vertical scrollbar is always present, then you can use css3 calc property to make the thead cells align with the tbody cells.
table.tableSection thead {
padding-right:18px; /* 18px is approx. value of width of scroll bar */
width: calc(100% - 18px);
}
You can do the same by detecting presence of scrollbar using javascript and applying the above styles.