I need to create a table with a fixed header and scrollable body; this should be done using only HTML and CSS, no JavaScript or other extravagant solutions. It should work on all major browsers, although there is no need for it to support really old ones like IE6.
I know this question has many duplicates, both here and on other sites; I also know various solutions have been posted everywhere; a quick search will turn up a dozen of them.
However, many of them don't really work as required, while all the ones I could find that actually work seem to have a very specific requirement: column width should be stated at design time (either in pixels or %), otherwise header cells and body cells become misaligned; and while this is ok in many cases, sometimes you really can't know the proper column and table width until the table is populated at runtime.
Given a table such as the following one:
<table>
<thead>
<tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th></tr>
</thead>
<tbody>
<tr><td>Row 1 - Col 1</td><td>Row 1 - Col 2</td><td>Row 1 - Col 3</td><td>Row 1 - Col 4</td></tr>
<tr><td>Row 2 - Col 1</td><td>Row 2 - Col 2</td><td>Row 2 - Col 3</td><td>Row 2 - Col 4</td></tr>
<tr><td>Row 3 - Col 1</td><td>Row 3 - Col 2</td><td>Row 3 - Col 3</td><td>Row 3 - Col 4</td></tr>
<tr><td>Row 4 - Col 1</td><td>Row 4 - Col 2</td><td>Row 4 - Col 3</td><td>Row 4 - Col 4</td></tr>
<tr><td>Row 5 - Col 1</td><td>Row 5 - Col 2</td><td>Row 5 - Col 3</td><td>Row 5 - Col 4</td></tr>
<tr><td>Row 6 - Col 1</td><td>Row 6 - Col 2</td><td>Row 6 - Col 3</td><td>Row 6 - Col 4</td></tr>
<tr><td>Row 7 - Col 1</td><td>Row 7 - Col 2</td><td>Row 7 - Col 3</td><td>Row 7 - Col 4</td></tr>
<tr><td>Row 8 - Col 1</td><td>Row 8 - Col 2</td><td>Row 8 - Col 3</td><td>Row 8 - Col 4</td></tr>
<tr><td>Row 9 - Col 1</td><td>Row 9 - Col 2</td><td>Row 9 - Col 3</td><td>Row 9 - Col 4</td></tr>
<tr><td>Row 10 - Col 1</td><td>Row 10 - Col 2</td><td>Row 10 - Col 3</td><td>Row 10 - Col 4</td></tr>
</tbody>
</table>
Is it possible to create a CSS-only solution that will satisfy the following requirements?
- The header must stay fixed at the top.
- The body must be vertically scrollable if all rows can't be displayed at once.
- All the cells, both in header and body, must be correctly aligned.
- It should work if table width and column width are not known at design time.