Thursday, August 02, 2018

HTML Table Scrollable Tbody

HTML tables can display rows and columns of data in a nicely excel like layout. With CSS, you can make beautiful tables. With huge rows of data, the header tends to be scrolled out of the screen making it difficult to know what the column represents.

Using CSS, you can actually fix the header and able to scroll the data. The trick is to use THEAD and TBODY with CSS.

For THEAD and TBODB, you need to use Display: Block. For TBODY only you need to use overflow-y: auto so that it could scroll up and down.

The problem with this arrangement is that the column width is uncontrollable especially when a column data is all empty. THEAD columns cannot sync with TBODY. Its really painful to have it working yet not able to align the column widths. I wonder why it is still not fixed.

One way to align the tables is to use Javascript. However, if user set to not allow JavaScript then the display is messed up. Therefore, a CSS way is more proper. The catch is to use fixed width columns. Many designer frown on such idea. There is no choice if you want to scroll.

However, Width:50px, for example, does not work well, the width still self adjusts according to the text length especially when the table size is limited. Putting too big a width also make the table look ugly. I used the following to at least make the width more consistent. It is not a cure but at least it looks more presentable.

The HTML/CSS used is as follows :-

  1. Assign the table with a class name.
  2. Set the table width to 100%, Table_Layout: fixed
  3. use table.classname thead to define display:block
  4. use table.classname tbody to define display:block and overflow-y:auto
  5. use table.classname th:nth-child(x), table.classname td:nth-child(x) to define the min-width and other styles.
Item 5 above actually forces both header and body column as defined by x to the same size. Assign a minimum size (min-width) to the column so that it will accommodate the longest single word text in the column (text with spaces will wrap by default). It will take a while to adjust it but at least the columns will align if the tbody cells are empty. Each column must have a corresponding width setting.

Until such a time when W3C solved the scrollable table issue, this is probably the make-do way. Others might have a better solution but this one is an accumulation of various designer's idea.





No comments:

Post a Comment