Does anyone know how to make a table with a fixed header row and scrollable body rows? I'm using twitter bootstrap if that matters.
This is an example of what I'm trying to create:
http://www.siteexperts.com/tips/html/ts04/page1.asp
All the examples I've seen break it into two separate tables. Was wondering if anyone has a more elegant solution.
Twitter bootstrap also automatically adjusts the column sizes based on content so that's another reason I'd like to keep it in one table
By setting postion: sticky and top: 0, we can create a fixed header on a scroll in HTML tables.
Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element). Then add the data-target attribute with a value of the id or the class name of the navigation bar ( . navbar ). This is to make sure that the navbar is connected with the scrollable area.
Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)
<table id="tableHeader" class="table" style="table-layout:fixed"> <thead> <tr> <th>Col1</th> ... </tr> </thead> </table> <div style="overflow-y:auto;"> <table id="tableData" class="table table-condensed" style="table-layout:fixed"> <tbody> <tr> <td>data</td> ... </tr> </tbody> </table> </div>
Demo JSFiddle
The content table div needs overflow-y:auto
, for vertical scroll bars. Had to use table-layout:fixed
, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.
Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.
// ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS $(function () { //copy width of header cells to match width of cells with data //so they line up properly var tdHeader = document.getElementById("tableHeader").rows[0].cells; var tdData = document.getElementById("tableData").rows[0].cells; for (var i = 0; i < tdData.length; i++) tdHeader[i].style.width = tdData[i].offsetWidth + 'px'; });
Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/
Usage:
$('selector').fixedHeaderTable({ fixedColumn: 1 });
Set the fixedColumn
option if you want any number of columns to be also fixed for horizontal scrolling.
EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.
EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With