07 October 2008

HTML: Scroll table contents without scrolling headers

 

I stumbled upon this quite by accident: all you need do is put the content you want scrolled inside a tbody tag, with style='height:nn;overflow-y:auto' where nn is the height you want your content. The tr containing your headers goes outside this tbody. This has been obvious all along to people who understand CSS, but I'm only starting to get to grips with this stuff. Here's an example, hit view source to see how it works:
foobar
0x
1y
2z
3x
4y
5z
6x
7y
8z
9x
Beats a zillion lines of js and css to do the same thing, no? It works for Firefox 3, I haven't tested it elsewhere. If anybody out there still has IE, please let me know if it works! Update : if you want the whole table to scroll horizontally, too keeping the headers aligned with their columns (thanks, Olivier), put the it in a div with style='width:nn;overflow-x:auto'. Thus:
foobarbaz
000.00xxxtoto-titi
100.00yyytiti-didi
200.00zzzdidi-dodo
300.00xxxdodo-toto
400.00yyytoto-titi
500.00zzztiti-didi
600.00xxxdidi-dodo
700.00yyydodo-toto
800.00zzztoto-titi
900.00xxxtiti-didi
It's not so pretty - the vertical scrollbar is visible only if you've scrolled horizontally all the way to the right. But given that you can scroll with the keyboard or mouse wheel, perhaps that's not such a terrible thing ...

4 comments:

  1. OK! But the issue we had was when there is also a horizontal scrollbar. The header was then not scrolling at all.
    Yes I know, the user aint' gonna need it but you know "them"... they really wanted it :-(

    ReplyDelete
  2. @Olivier - see update (the comment box doesn't let me include table tags)

    ReplyDelete
  3. Interesting, the vertical scroll does not work with Safari, but the horizontal one does.

    ReplyDelete
  4. @laurent ... ouch, you're right! who is being non-compliant in this case?

    ReplyDelete