I am writing a page where I need an html table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table.
I want it to look like method 2 in this url: http://www.cssplay.co.uk/menu/tablescroll.html
I have tried doing this but no scrollbar appears:
<table border=1 id="qandatbl" align="center">
<tr>
<th class="col1">Question No</th>
<th class="col2">Option Type</th>
<th class="col1">Duration</th>
</tr>
<tbody>
<tr>
<td class='qid'></td>
<td class="options"></td>
<td class="duration"></td>
</tr>
</tbody>
</table>
CSS:
tbody {
height:80em;
overflow:scroll;
}
You have to insert your table into a div that it has fixed size, and in div style you have to set overflow:scroll.
Worth noting, that depending on your purpose (mine was the autofill results of a searchbar) you may want the height to be changeable, and for the scrollbar to only exist if the height exceeds that.
If you want that, replace
height: x;
withmax-height: x;
, andoverflow:scroll
withoverflow:auto
.Additionally, you can use
overflow-x
andoverflow-y
if you want, and obviously the same thing works horizontally withwidth : x;
I resolved this problem by separating my content into two tables.
One table is the header row.
The seconds is also
<table>
tag, but wrapped by<div>
with static height and overflow scroll.If you get to the point where all the mentioned solutions don't work (as it got for me), do this:
Like this, in your
HTML
Then style the second table's parent to allow vertical scroll, in your
CSS
Something like this?
http://jsfiddle.net/TweNm/
The idea is to wrap the
<table>
in a non-statically positioned<div>
which has anoverflow:auto
CSS property. Then position the elements in the<thead>
absolutely.The accepted answer provided a good starting point, but if you resize the frame, change the column widths, or even change the table data, the headers will get messed up in various ways. Every other example I've seen has similar issues, or imposes some serious restrictions on the table's layout.
I think I've finally got all these problems solved, though. It took a lot of CSS, but the final product is about as reliable and easy to use as a normal table.
Here's an example that has all the required features to replicate the table referenced by the OP: jsFiddle
The colors and borders would have to be changed to make it identical to the reference. Information on how to make those kinds of changes is provided in the CSS comments.
Here's the code: