Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to keep the header row of a table from scrolling when table content gets too tall.

Table Formatting

How to keep the header row of a table from scrolling when table content gets too tall.

by  Einstein47  Posted    (Edited  )
We have all had a page with a table where the content is loaded dynamically and we don't have any idea of the number of rows. It becomes especially difficult when we want the header row to stay fixed while the rest of the content is scrolled. I found this trick that works in IE 5.5+ (untested in other browsers).

Code:
[blue]<div style="height: 250px; overflow: auto;">[/blue]
<table [red]cellspacing="2"[/red]>
  <tr [green]style="position: relative; top: expression(this.offsetParent.scrollTop-[/green][red]2[/red][green]);"[/green]>
    <th style="background: #003366; color: white;"> Table Title </th>
    .
    .
    .
  </tr>
  <tr>
    <td> content </td>
  </tr>
    .
    .
    .
</table>
[blue]</div>[/blue]

What this is doing is putting your table inside a [blue]DIV[/blue] tag of fixed height (you can change this to fit your page - either % or px work best), but allowing for the content to be scrollable. Then the style added on the first [green]TR[/green] tag instructs the browser to dynamically position that row at the top of the [blue]DIV[/blue] regardless of the scrolling.

There is one important thing to note. The value in your [red]cellspacing[/red] must match the value at the end of the expression in the TR style. If you don't specify a value in the TABLE for cellspacing it will [red]default to 2[/red]. Play with it to see the different results.

This is very useful when using PHP, ASP, JSP that can generate exceedingly tall tables. The only slight defect is a visual blur that happens while scrolling. However that stops when the scrolling stops. Also be aware that if you have SELECT dropdown lists in the content of your table, they will be displayed above (in the z-order) the header row (a condition that exists in all browsers).

Good luck, and happy coding.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top