1

I have a big table inside a div with scroll-x and scroll-y. What I want is to just make the table header fixed when scrolling in y-axis.

I can set the table header at the top of the div but it is not respecting overflow-x. and also the table head column width needs to be same as the column of the content.

How can I attain this?

byJeevan
  • 3,728
  • 3
  • 37
  • 60
user2742122
  • 603
  • 2
  • 8
  • 15

1 Answers1

4

Here is a demo Fixed Header Demo .

I explored your problem and got a solution [I believe there is no pure css solution exits.!]. Also, You are most welcome to optimize this.

//Script

 <script>

 var maxw = 0;
 $(document).ready( function () {

  $('.Top2').bind('scroll', function(){
     $(".Top1").scrollLeft($(this).scrollLeft());
  });

      var len = $("table.head > tbody").find("> tr:first > td").length;
       for(i=0; i<len;i++) {
           maxval(i);
       maxw = 0 ;
       }     

   });

function maxval(index) {

    $("table").find('tr').each(function (i, el) {
                var $tds = $(this).find('td');
                w = $tds.eq(index).width(); 
                if(w>maxw){
                maxw = w; //Get max width for the column i
                }       
    });
   myf(maxw,index); // Set the css according to 'td'
}

function myf(maxw,index){
 $("table").find('tr').each(function (i, el) {
     var $tds =  $(this).find('td');
     $tds.eq(index).css("padding-right", maxw- ($tds.eq(index).width()));  // patch : Is any other way?
 });
}
   </script>

Also check my updated fiddle.

byJeevan
  • 3,728
  • 3
  • 37
  • 60