How: Fixed table header with ONE table (without jQuery)

I know there are at least 3 dozen questions like this one on stackoverflow, and yet I couldn't do it:

A simple table where thead is fixed / fixed at the top, and the throne scrolls. I tried so much in the past days, and now I am here, screaming for help.

The solution should work in IE8 + and the latest FF, Chrome and Safari. The difference with the other possible duplicates like this is that I don't want to use two nested tables or jQuery (plain javascript is fine though).

Demonstration of what I want:
http://www.imaputz.com/cssStuff/bigFourVersion.html

The problem in IE is not working, and it would be nice for me to use some JS.

+7
source share
2 answers

OK I understood:

You need to wrap the table in two DIVs:

<div class="outerDIV"> <div class="innerDIV"> <table></table> </div> </div> 

CSS for DIVs:

 .outerDIV { position: relative; padding-top: 20px; //height of your thead } .innerDIV { overflow-y: auto; height: 200px; //the actual scrolling container } 

The reason is because you basically make the inner DIV scrollable and pull the THEAD out of it, sticking it to the outer DIV.

Now bind thead to an external thead by specifying it

 table thead { display: block; position: absolute; top: 0; left: 0; } 

tbody should have display: block .

Now you will notice that scrolling works, but the widths are completely confused. It was Javascript. You can choose how you want to assign it. I myself gave TH a fixed width in the table and built a simple script that takes the width and assigns them to the first TD row in tbody .

Something like this should work:

 function scrollingTableSetThWidth(tableId) { var table = document.getElementById(tableId); ths = table.getElementsByTagName('th'); tds = table.getElementsByTagName('td'); if(ths.length > 0) { for(i=0; i < ths.length; i++) { tds[i].style.width = getCurrentComputedStyle(ths[i], 'width'); } } } function getCurrentComputedStyle(element, attribute) { var attributeValue; if (window.getComputedStyle) { // class A browsers var styledeclaration = document.defaultView.getComputedStyle(element, null); attributeValue = styledeclaration.getPropertyValue(attribute); } else if (element.currentStyle) { // IE attributeValue = element.currentStyle[vclToCamelCases(attribute)]; } return attributeValue; } 

With jQuery, of course, that would be a lot easier, but so far I have not been allowed to use a third-party library for this project.

+14
source

Perhaps we need to change the method for archiving this purpose. Such as the:

 <div><ul><li>1</li><li>2</li></ul></div> //make it fixed <table> <thead> <tr><th>1</th><th>2</th></tr> </thead> <tfoot></tfoot> <tbody></tbody> </table> 

Of course, this is not good for sematic. But this is the easiest way without js or jq. Don't you think so?

-one
source

All Articles