jump Index ScientificPsychic.com
Scientific Psychic Expand your mind

2009-07-13
 

HTML and CSS Scrolling table with fixed heading


In web design, you often have to display a table that is too long and ruins the aesthetics of the page. The ideal thing to do is to scroll the body of the table while leaving the headings fixed. The design of the HTML didn't quite get it right. You would think that the following code would solve the problem by just scrolling the body enclosed within the <tbody> tags, but it does not work in any browser.

This code does NOT work:

<table cellspacing="0" cellpadding="1" border="1" width="300" >
<thead>
<tr>
<th>col 1 heading</th>
<th>col 2 heading</th>
</tr>
</thead>
<tbody style="height:48px; overflow:auto;">
<tr>
<td>col 1 data 1</td>
<td>col 2 data 1</td>
</tr>
<tr>
<td>col 1 data 2</td>
<td>col 2 data 2</td>
</tr>
<tr>
<td>col 1 data 3</td>
<td>col 2 data 3</td>
</tr>
</tbody>
</table>


There are solutions posted on the Internet that solve the problem by using JavaScript to cope with browser idiosyncrasies, but they are not general solutions.

It is possible to have a table with a scrolling body and fixed header with only HTML and CSS. The solution is to use three tables. An outer table consists of two rows. The top row contains a table for the heading and the bottom row contains a <div> containing the table for the scrollable body. The outer table and the <div> container have to be 25 pixels wider than the tables for the heading and the body to allow room for the vertical scroll bar. The column widths of the tables are defined through CSS.

The following code works for all browsers (Internet Explorer, Firefox, Safari, Opera):


<table cellspacing="0" cellpadding="0" border="0" width="325">
<tr>
<td>
<table cellspacing="0" cellpadding="1" border="1" width="300" >
<tr>
<th>col 1 heading</th>
<th>col 2 heading</th>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<div style="width:325px; height:48px; overflow:auto;">
<table cellspacing="0" cellpadding="1" border="1" width="300" >
<tr>
<td>col 1 data 1</td>
<td>col 2 data 1</td>
</tr>
<tr>
<td>col 1 data 2</td>
<td>col 2 data 2</td>
</tr>
<tr>
<td>col 1 data 3</td>
<td>col 2 data 3</td>
</tr>
</table>
</div>
</td>
</tr>
</table>


Look at the code for the table above




© Copyright  - Antonio Zamora