0

I have been looking how to make my table header to stick on top and how to make the first column also stick (just like freeze pane on excel). I managed to find some examples here and here and implement it with my own way. The result is something like this https://jsfiddle.net/Lz1rujc1/2/

However, with this approach I have some problems:

  1. How do I set the header column <th> so that it has the same width with the content <td>?
  2. Is there anyway to make the first column to stick on the left side all the time when i use the horizontal scroll (just like here)?
Community
  • 1
  • 1
Hello_World
  • 101
  • 3
  • 10

1 Answers1

0

Generally speaking, there is no simple solution to your problem, certainly not without some javascript.

On one hand, in order to make the first row (the header) fixed, you have to specify position: absolute / fixed. On the other hand, if you do, you lose the automatic html table width allocation. That means you have 2 options:

  • You can have a table with fixed column width, and then just set the first row to have position absolute / fixed.
  • Or keep the automatic table width allocation, set the first row to position fixed, but lose the synchronization between header cell widths and normal table cell widths, which just looks awful.

There are many solutions and options to overcome this annoying problem, some of those you quoted in your question. You may want to check these aswell:

http://www.fixedheadertable.com/

how do I create an HTML table with fixed/frozen left column and scrollable body?

The solution I ended up using was to use 2 tables, one for the header and one for the content. To solve the width problem, I used some jquery to dynamically copy the width value from the content table and set it to the header table. Something like this:

//freeze pane
var updateFreezePane = function() {

    var originTable = $("#original-table-id");
    var tableOffset = originTable.offset().top;
    var tableWidth = originTable.width();
    var $fixedHeader = $("#fixed-header");
    $fixedHeader.css('top',tableOffset + 'px');
    $fixedHeader.width(tableWidth);
    var offset = $(this).scrollTop();
    var $header = $("#original-table-id > thead");

    if (offset > 0) {
        $fixedHeader.show();

        var $fixedHeaderThs = $fixedHeader.find('tr > th');

        //dynamically copy the width of each original th to the fixed header th

        $.each($header.find('tr > th'), function(ind,val){
          var original_width = $(val).width();
          var original_padding = $(val).css("padding");
          $($fixedHeaderThs[ind]).width(original_width);
        });
    }
    else {
        $fixedHeader.hide();
    }
};

$(window).bind("scroll", updateFreezePane);
$(window).bind("resize", updateFreezePane);
Community
  • 1
  • 1