[javascript] How can I let a table's body scroll but keep its head fixed in place?

I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?

This question is related to javascript html css html-table

The answer is


I saw Sean Haddy's excellent solution to a similar question and took the liberty of making some edits:

  • Use classes instead of ID, so one jQuery script could be reused for multiple tables on one page
  • Added support for semantic HTML table elements like caption, thead, tfoot, and tbody
  • Made scrollbar optional so it won't appear for tables that are "shorter" than the scrollable height
  • Adjusted scrolling div's width to bring the scrollbar up to the right edge of the table
  • Made concept accessible by
    • using aria-hidden="true" on injected static table header
    • and leaving original thead in place, just hidden with jQuery and set aria-hidden="false"
  • Showed examples of multiple tables with different sizes

Sean did the heavy lifting, though. Thanks to Matt Burland, too, for pointing out need to support tfoot.

Please see for yourself at http://jsfiddle.net/jhfrench/eNP2N/


This caused me huge headaches trying to implement such a grid for an application of ours. I tried all the various techniques out there but they each had problems. The closest I came was using a jQuery plugin such as Flexigrid (look on http://www.ajaxrain.com for alternatives), but this doesn't seem to support 100% wide tables which is what I needed.

What I ended up doing was rolling my own; Firefox supports scrolling tbody elements so I browser sniffed and used appropriate CSS (setting height, overflow etc... ask if you want more details) to make that scroll, and then for other browsers I used two separate tables set to use table-layout: fixed which uses a sizing algorithm that is guarenteed not to overflow the stated size (normal tables will expand when content is too wide to fit). By giving both tables identical widths I was able to get their columns to line up. I wrapped the second one in a div set to scroll and with a bit of jiggery pokery with margins etc managed to get the look and feel I wanted.

Sorry if this answer sounds a bit vague in places; I'm writing quickly as I don't have much time. Leave a comment if you want me to expand any further!


Here's a code that really works for IE and FF (at least):

<html>
<head>
    <title>Test</title>
    <style type="text/css">
        table{
            width: 400px;
        }
        tbody {
            height: 100px;
            overflow: scroll;
        }
        div {
            height: 100px;
            width: 400px;
            position: relative;
        }
        tr.alt td {
            background-color: #EEEEEE;
        }
    </style>
    <!--[if IE]>
        <style type="text/css">
            div {
                overflow-y: scroll;
                overflow-x: hidden;
            }
            thead tr {
                position: absolute;
                top: expression(this.offsetParent.scrollTop);
            }
            tbody {
                height: auto;
            }
        </style>
    <![endif]--> 
</head>
<body>
    <div >
        <table border="0" cellspacing="0" cellpadding="0">
            <thead>
                <tr>
                    <th style="background: lightgreen;">user</th>
                    <th style="background: lightgreen;">email</th>
                    <th style="background: lightgreen;">id</th>
                    <th style="background: lightgreen;">Y/N</th>
                </tr>
            </thead>
            <tbody align="center">
                <!--[if IE]>
                    <tr>
                        <td colspan="4">on IE it's overridden by the header</td>
                    </tr>
                <![endif]--> 
                <tr>
                    <td>user 1</td>
                    <td>[email protected]</td>
                    <td>1</td>
                    <td>Y</td>
                </tr>
                <tr class="alt">
                    <td>user 2</td>
                    <td>[email protected]</td>
                    <td>2</td>
                    <td>N</td>
                </tr>
                <tr>
                    <td>user 3</td>
                    <td>[email protected]</td>
                    <td>3</td>
                    <td>Y</td>
                </tr>
                <tr class="alt">
                    <td>user 4</td>
                    <td>[email protected]</td>
                    <td>4</td>
                    <td>N</td>
                </tr>
                <tr>
                    <td>user 5</td>
                    <td>[email protected]</td>
                    <td>5</td>
                    <td>Y</td>
                </tr>
                <tr class="alt">
                    <td>user 6</td>
                    <td>[email protected]</td>
                    <td>6</td>
                    <td>N</td>
                </tr>
                <tr>
                    <td>user 7</td>
                    <td>[email protected]</td>
                    <td>7</td>
                    <td>Y</td>
                </tr>
                <tr class="alt">
                    <td>user 8</td>
                    <td>[email protected]</td>
                    <td>8</td>
                    <td>N</td>
                </tr>
            </tbody>
        </table>
    </div>
</body></html>

I've changed the original code to make it clearer and also to put it working fine in IE and also FF..

Original code HERE


Edit:   This is a very old answer and is here for prosperity just to show that it was supported once back in the 2000's but dropped because browsers strategy in the 2010's was to respect W3C specifications even if some features were removed: Scrollable table with fixed header/footer was clumsily specified before HTML5.


Bad news

Unfortunately there is no elegant way to handle scrollable table with fixed thead/tfoot because HTML/CSS specifications are not very clear about that feature.

Explanations

Although HTML 4.01 Specification says thead/tfoot/tbody are used (introduced?) to scroll table body:

Table rows may be grouped [...] using the THEAD, TFOOT and TBODY elements [...]. This division enables user agents to support scrolling of table bodies independently of the table head and foot.

But the working scrollable table feature on FF 3.6 has been removed in FF 3.7 because considered as a bug because not compliant with HTML/CSS specifications. See this and that comments on FF bugs.

Mozilla Developer Network tip

Below is a simplified version of the MDN useful tips for scrollable table
see this archived page or the current French version

<style type="text/css">
table {
  border-spacing: 0;              /* workaround */
}
tbody {
  height: 4em;                    /* define the height */
  overflow-x: hidden;             /* esthetics */
  overflow-y: auto;               /* allow scrolling cells */
}
td {
  border-left:   1px solid blue;  /* workaround */
  border-bottom: 1px solid blue;  /* workaround */
}
</style>

<table>
    <thead><tr><th>Header
    <tfoot><tr><th>Footer
    <tbody>
        <tr><td>Cell 1    <tr><td>Cell 2
        <tr><td>Cell 3    <tr><td>Cell 4
        <tr><td>Cell 5    <tr><td>Cell 6
        <tr><td>Cell 7    <tr><td>Cell 8
        <tr><td>Cell 9    <tr><td>Cell 10
        <tr><td>Cell 11   <tr><td>Cell 12
        <tr><td>Cell 13   <tr><td>Cell 14
    </tbody>
</table>

However MDN also says this does not work any more on FF :-(
I have also tested on IE8 => table is not scrollable either :-((


Sorry I haven.t read all replies to your question.

Yeah here the thing you want (I have done already)

You can use two tables, with same class name for similar styling, one only with table head and another with your rows. Now put this table inside a div having fixed height with overflow-y:auto OR scroll.


I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.

Basically:

  1. In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header

  2. In CSS, convert the table parts to blocks

  3. In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height

Here's the javascript and a jsFiddle DEMO.

// get table width and match the mask width

function setMaskWidth() { 
  if (document.getElementById('mask') !==null) {
    var tableWidth = document.getElementById('theTable').offsetWidth;

    // match elements to the table width
    document.getElementById('mask').style.width = tableWidth + "px";
   }
}

function fixTop() {

  // get height of page content 
  function getScrollY() {
      var y = 0;
      if( typeof ( window.pageYOffset ) == 'number' ) {
        y = window.pageYOffset;
      } else if ( document.body && ( document.body.scrollTop) ) {
        y = document.body.scrollTop;
      } else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
        y = document.documentElement.scrollTop;
      }
      return [y];
  }  

  var y = getScrollY();
  var y = y[0];

  if (document.getElementById('mask') !==null) {
      document.getElementById('mask').style.height = y + "px" ;

      if (document.all && document.querySelector && !document.addEventListener) {
        document.styleSheets[1].rules[0].style.top = y + "px" ;
      } else {
        document.styleSheets[1].cssRules[0].style.top = y + "px" ;
      }
  }

}

window.onscroll = function() {
  setMaskWidth();
  fixTop();
}

Live JsFiddle

It is possible with only HTML & CSS

_x000D_
_x000D_
table.scrollTable {_x000D_
  border: 1px solid #963;_x000D_
  width: 718px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr {_x000D_
  height: 30px;_x000D_
  background: #c96;_x000D_
}_x000D_
_x000D_
thead.fixedHeader tr th {_x000D_
  border-right: 1px solid black;_x000D_
}_x000D_
_x000D_
tbody.scrollContent {_x000D_
  display: block;_x000D_
  height: 262px;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
  background: #eee;_x000D_
  border-right: 1px solid black;_x000D_
  height: 25px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent tr.alternateRow td {_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th {_x000D_
  width: 233px;_x000D_
}_x000D_
_x000D_
thead.fixedHeader th:last-child {_x000D_
  width: 251px;_x000D_
}_x000D_
_x000D_
tbody.scrollContent td {_x000D_
  width: 233px;_x000D_
}
_x000D_
<table cellspacing="0" cellpadding="0" class="scrollTable">_x000D_
  <thead class="fixedHeader">_x000D_
    <tr class="alternateRow">_x000D_
      <th>Header 1</th>_x000D_
      <th>Header 2</th>_x000D_
      <th>Header 3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody class="scrollContent">_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>And Repeat 1</td>_x000D_
      <td>And Repeat 2</td>_x000D_
      <td>And Repeat 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Cell Content 1</td>_x000D_
      <td>Cell Content 2</td>_x000D_
      <td>Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>More Cell Content 1</td>_x000D_
      <td>More Cell Content 2</td>_x000D_
      <td>More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="normalRow">_x000D_
      <td>Even More Cell Content 1</td>_x000D_
      <td>Even More Cell Content 2</td>_x000D_
      <td>Even More Cell Content 3</td>_x000D_
    </tr>_x000D_
    <tr class="alternateRow">_x000D_
      <td>End of Cell Content 1</td>_x000D_
      <td>End of Cell Content 2</td>_x000D_
      <td>End of Cell Content 3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_


If its ok to use JavaScript here is my solution Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!

Tested in: Opera, Chrome, Safari, FF, IE5.5(Epic script fail), IE6, IE7, IE8, IE9

//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width
$(document).ready(function () {
    $("table.Scrollify").each(function (index, element) {
        var header = $(element).children().children().first();
        var headerHtml = header.html();
        var width = $(element).outerWidth();
        var height = parseInt($(element).css("height")) - header.outerHeight();
        $(element).height("auto");
        header.remove();
        var html = "<table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"><tr>" + headerHtml +
                         "</tr></table><div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\">" +
                         $(element).parent().html() + "</div>";

        $(element).parent().html(html);
    });
});


//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels
//License: Apache License, version 2
function scrollbarWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}

Edit: Fixed height.


For me, nothing related to scrolling really worked until I removed the width from the table CSS. Originally, the table CSS looked like this:

.table-fill {
    background: white;
    border-radius:3px;
    border-collapse: collapse;
    margin: auto;
    width: 100%;
    max-width: 800px;
    padding:5px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
    animation: float 5s infinite;
}

As soon as I removed the width:100%; all scrolling features started working.


Not sure if anyone is still looking at this but they way I have done this previously is to use two tables to display the single original table - the first just the original table title line and no table body rows (or an empty body row to make it validate).

The second is in a separate div and has no title and just the original table body rows. The separate div is then made scrollable.

The second table in it's div is placed just below the first table in the HTML and it looks like a single table with a fixed header and a scrollable lower section. I have only tested this in Safari, Firefox and IE (latest versions of each in Spring 2010) but it worked in all of them.

The only issue it had was that the first table would not validate without a body (W3.org validator - XHTML 1.0 strict), and when I added one with no content it causes a blank row. You can use CSS to make this not visible but it still eats up space on the page.


The main problem I had with the suggestions above was being able to plug in tablesorter.js AND being able to float the headers for a table constrained to a specific max size. I eventually stumbled across the plugin jQuery.floatThead which provided the floating headers and allowed sorting to continue to work.

It also has a nice comparison page showing itself vs similar plugins.


I found DataTables to be quite flexible. While its default version is based on jquery, there is also an AngularJs plugin.


Here's my alternative. It also uses different DIVs for the header, body and footer but synchronised for window resizing and with searching, scrolling, sorting, filtering and positioning:

My CD lists

Click on the Jazz, Classical... buttons to see the tables. It's set up so that it's adequate even if JavaScript is turned off.

Seems OK on IE, FF and WebKit (Chrome, Safari).


Have you tried using thead and tbody, and setting a fixed height on tbody with overflow:scroll?

What are your target browsers?

EDIT: It worked well (almost) in firefox - the addition of the vertical scrollbar caused the need for a horizontal scrollbar as well - yuck. IE just set the height of each td to what I had specifed the height of tbody to be. Here's the best I could come up with:

<html>
    <head>
    <title>Blah</title>
    <style type="text/css">
    table { width:300px; }
    tbody { height:10em;  overflow:scroll;}
    td { height:auto; }
    </style>
    </head>
    <body>
    <table>
        <thead>
            <tr>
              <th>One</th><th>Two</th>
              </td>
            </tr>
        </thead>
        <tbody>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
            <tr><td>Data</td><td>Data</td></tr>
        </tbody>
    </table>
    </body>
</html>

I had to find the same answer. The best example I found is http://www.cssplay.co.uk/menu/tablescroll.html - I found example #2 worked well for me. You will have to set the height of the inner table with Java Script, the rest is CSS.


What you need is :

1) have a table body of limited height as scroll occurs only when contents is bigger than the scrolling window. However tbody cannot be sized, and you have to display it as a block to do so:

tbody {
   overflow-y: auto;
   display: block;
   max-height: 10em;    // For example
}

2) Re-sync table header and table body columns widths as making the latter a block made it an unrelated element. The only way to do so is to simulate synchronization by enforcing the same columns width to both.

However, since tbody itself is a block now, it can no longer behave like a table. Since you still need a table behavior to display you columns correctly, the solution is to ask for each of your rows to display as individual tables:

thead {         
   display: table;  
   width: 100%;     // Fill the containing table
}
tbody tr {
   display: table;
   width: 100%;     // Fill the containing table
}

(Note that, using this technique, you won't be able to span across rows anymore).

Once that done, you can enforce column widths to have the same width in both thead and tbody. You could not that:

  • individually for each column (through specific CSS classes or inline styling), which is quite tedious to do for each table instance ;
  • uniformly for all columns (through th, td { width: 20%; } if you have 5 columns for example), which is more practical (no need to set width for each table instance) but cannot work for any columns count
  • uniformly for any columns count, through a fixed table layout.

I prefer the last option, which requires adding:

thead {
   table-layout: fixed;   // Same layout for all cells
}
tbody tr {
   table-layout: fixed;   // Same layout for all cells
}
th, td {
   width: auto;   // Same width for all cells, if table has fixed layout
}    

See a demo here, forked from the answer to this question.


If you have low enough standards ;) you could place a table that contains only a header directly above a table that has only a body. It won't scroll horizontally, but if you don't need that...


This solution works in Chrome 35, Firefox 30 and IE 11 (not tested other versions)

Its pure CSS: http://jsfiddle.net/ffabreti/d4sope1u/

Everything is set to display:block, table needs a height:

    table {
        overflow: scroll;
        display: block;    /*inline-block*/
        height: 120px;
    }
    thead > tr  {
        position: absolute;
        display: block;
        padding: 0;
        margin: 0;
        top: 0;
        background-color: gray;
    }
    tbody > tr:nth-of-type(1) {
        margin-top: 16px;
    }
    tbody tr {
        display: block;
    }

    td, th {
        width: 70px;
        border-style:solid;
        border-width:1px;
        border-color:black;
    }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?