Saturday 15 June 2013

Fixed Table Headers

Persistent table headers our more notorious than one might think. A simple position:fixed on the first row won't do the trick. Now you might ask, why another tutorial on how to fix table headers, when there are many existing solutions.

What I needed to do was a bit different. It was table inside an enterprise web-application, and every column had been allotted different widths, many of the existing CSS/JS solutions required knowing the width of the table before hand to work. So I had to cook up something else.

Position Fixed on Table Header

Whenever we are faced with a situation where we have to make a fixed table header, we first think about fixed positioning. Well this is what happens when we have fixed positioning.


 So, What's the solution?

I observed that if every cell of row had a defined width, It would not collapse like above. But as I said, dynamic tables were not helping. So I created some JavaScript(it uses jQuery too) to give every cell in the first row a width of the corresponding cell in the second row. Here is the code.


Yup that's it. 16 lines of JavaScript to the rescue. The only "Magic" happening here is the 'spacer' row, which    keeps the house in order. As we know that fixed positioning takes the element out of the flow of the DOM, spacer ensures that the second row does not slip below the first.

Any advantages?

There are many advantages IMO, here they are:

  • No fixed width! it does not limit you to have a fixed width on your table, or know it before hand.
  • Runs once. There are solutions that re-position the header every time it slips out of the view.
Tested on Chrome, Firefox IE 9.
Not on mobiles
That's it. Share your views..

No comments:

Post a Comment