How to: Fixed Table Header with ONE table (no jQuery)

Ok i got it:

You need to wrap the table in two DIVs:

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

The CSS for the DIVs is this:

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

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

Now stick the thead to the outerDIV by giving it

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

The tbody needs to have display: block as well.

Now you’ll notice that the scrolling works, but the widths are completely messep up. That’s were Javascript comes in.
You can choose on your own how you want to assign it. I for myself gave the TH’s in the table fixed widths and built a simple script which takes the width and assigns them to the first TD-row in the 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 this would be a lot easier but for now i was not allowed to use a third party library for this project.

Leave a Comment