Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed <thead> in <table>

Tags:

html

jquery

css

<table border="1" style="height:50px; overflow:auto;">
  <thead>
    <tr>
      <th>Col 1
      </th>
      <th>Col 2
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Cell 3
      </td>
      <td>Cell 4
      </td>
    </tr>
    <tr>
      <td>Cell 5
      </td>
      <td>Cell 6
      </td>
    </tr>
  </tbody>
</table>

I'd like the above table to be of 50px height so the scrollers would kick in when the content grows, but I'd also like table headers (thead) to be fixed always on top, while other content can be scrollable. Is there an solution, preferable using jQuery?

Thanks in advance for your help.

like image 319
eozzy Avatar asked Dec 27 '09 13:12

eozzy


People also ask

How do I fix a header row in HTML table?

To freeze the row/column we can use a simple HTML table and CSS. HTML: In HTML we can define the header row by <th> tag or we can use <td> tag also. Below example is using the <th> tag. We also put the table in DIV element to see the horizontal and vertical scrollbar by setting the overflow property of the DIV element.

How do I fix the header of a table in CSS?

By setting postion: sticky and top: 0, we can create a fixed header on a scroll in HTML tables.


3 Answers

Found myself in need of similar functionality. Couldn't find anything light and simple, so I created the plugin myself: TH Float jQuery Plugin

I hope someone finds it useful.

like image 113
R. S. Avatar answered Oct 22 '22 21:10

R. S.


Here it is my trick. You have to change something in your html too.

The trick consists in inserting through js after the real scrolling thead, a secondary and identical thead positioned fixed. Cells widths are adjusted through js too.

Adjust the code on your needs.

CSS

thead.fixed {
  position: fixed;
}

HTML

<div style="overflow: auto;">
  <table id="my_table">
    <thead>
      <tr>
        <th>Head 1</th>
        <th>Head 2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Body 1</td>
        <td>Body 2</td>
      </tr>
    </tbody>
  </table>
</div>

jQuery

$( function() {
  fixListThead();
});
$(window).resize( function() {
  fixListThead();
});
var fixListThead = function() {
  $('#my_table thead.fixed').remove(); // Removes (if present) fixed thead when resizing
  var widths = [];
  $('#my_table thead th').each( function(i, element) {
    widths[i] = $(element).width();
  });
  $('<thead class="fixed">' + $('#my_table thead').html() + '</thead>').insertAfter($('#my_table thead'));
  $('#my_table thead.fixed th').each( function(i, element) {
    $(element).css('width', widths[i] + 'px');
  });
}
like image 3
panteo Avatar answered Oct 22 '22 19:10

panteo


Try this post: jQuery Scrollable, Sortable, Filterable table

It looks like they've got what you need (which is a freezable, scrollable jquery table).

like image 2
Mark Pope Avatar answered Oct 22 '22 21:10

Mark Pope