How can I let a table's body scroll but keep its head fixed in place?
Asked Answered
C

18

149

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?

Colleencollege answered 24/9, 2008 at 23:21 Comment(9)
there's lots of examples out there. this one is one of them.Leonor
I need to target IE6, IE7, FF, ... but especially IE unfortunatelyColleencollege
There's a lot of CSS hacks in there. It should be trivial to get working in IE7.Rescript
I'm interested in the answer for all browsers!Colleencollege
Only works in 5 and 5.5 near as I can tell.Transonic
This doesn't work in IE8 either. I tried native and compatibility mode and nothing works except for quirks mode.Wilterdink
It's not an answer because I can't test it, but what about having the CSS set tbody to scroll with a defined height?Hyperbole
your solution doesn't work if you don't specify <th> width inside <thead>Biak
"It should be trivial to get working in IE7." Jim, is that you? Are you my project manager? :)Swetlana
P
53

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.

Potato answered 29/9, 2008 at 21:36 Comment(5)
unfortunately, this method fails when you have a wide table (horizontal scroll). You'll have two horizontal scrollbars; one for the header and one for the data.Recognizance
your solution doesn't work if you don't specify <th> width inside <thead>Biak
To comply with (relatively) new Stack Overflow standards, could you edit this answer to include the relevant bits from the link?Hadria
Where's the source, Billy?Lucubration
It is impossible to synchronize column widths between the header and the (scrollable) table body without resorting to JavaScript or pre-defined values.Jewett
K
35

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

Krystynakshatriya answered 18/12, 2011 at 3:25 Comment(1)
very slick - most of the functionality work on my S3, android 4.0.4, but not the search/filterAlphonso
A
12

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/

Ame answered 11/10, 2012 at 18:55 Comment(3)
Good, but it screws up if you want a header and a footer!Ceroplastic
Thanks Matt, I made the adjustment.Ame
Alignment needs tweaking if you show td and th borders.Myocardium
G
11

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.e. same width for all).

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.

Gotland answered 11/5, 2014 at 15:26 Comment(1)
thanks for the explanation. It's beguiling how many ways something like this can be done and most of the answers just present some code and plunkr link, leaving you to figure it out for yourself.Outmoded
R
10

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>
Ripplet answered 24/9, 2008 at 23:23 Comment(6)
I need to target IE6, IE7, FF, ... but especially IE unfortunatelyColleencollege
Change the table so that it is less than 100% in width, say 99% and it will should take care of the problemWheeling
overflow-x: hidden; and overflow-y: auto also help.Heliport
are you sure this work ? I just checked, not working in ff or chrome.Yodle
This used to work in firefox, and it is the obvious and non-cludgy code. However, in more recent versions of firefox, it's broken.Jehovah
This does not work because "overflow" is only applicable to "block containers" (w3.org/TR/CSS21/visufx.html#overflow), and table boxes are not "block containers" (w3.org/TR/CSS21/visuren.html#block-boxes).Huynh
C
4

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 :-((

Cutshall answered 4/5, 2012 at 15:20 Comment(2)
MDN tips for scrollable table link is not relevant information it speaks about border-collapse. Maybe page was changes because 5 years passedNiggle
Thanks @Niggle I have finally found the original wiki page in the MDN history! My old answer seems now obsolete but for the prosperity the next generation of developers will know it was possible and easy to implement back in the 2000's ;-) CheersCutshall
O
3

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.

Ostrowski answered 6/8, 2010 at 15:47 Comment(1)
How would the extra row take up space still? It doesn't have to take up any screen space if you use display: none;, unless you mean space in the source..?Mundford
A
3

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;
    }
Antin answered 3/9, 2014 at 21:45 Comment(0)
A
2

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!

Affiche answered 24/9, 2008 at 23:30 Comment(1)
Sorry to resurrect this old thread, but I really need to know how you worked this out. I got FF working but not IE/WebKit browsers. Please help when you can.Potamic
T
2

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

Timisoara answered 24/1, 2011 at 19:34 Comment(1)
In IE7/8 this only works in Quirks Mode, and it stops working as soon as you add a doctype, i.e. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> Platinic
W
1

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).

Walston answered 3/3, 2011 at 8:44 Comment(0)
A
1

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.

Asuncion answered 19/7, 2012 at 11:12 Comment(0)
A
1

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.

Alligator answered 22/11, 2012 at 4:34 Comment(0)
C
1

Live JsFiddle

It is possible with only HTML & CSS

table.scrollTable {
  border: 1px solid #963;
  width: 718px;
}

thead.fixedHeader {
  display: block;
}

thead.fixedHeader tr {
  height: 30px;
  background: #c96;
}

thead.fixedHeader tr th {
  border-right: 1px solid black;
}

tbody.scrollContent {
  display: block;
  height: 262px;
  overflow: auto;
}

tbody.scrollContent td {
  background: #eee;
  border-right: 1px solid black;
  height: 25px;
}

tbody.scrollContent tr.alternateRow td {
  background: #fff;
}

thead.fixedHeader th {
  width: 233px;
}

thead.fixedHeader th:last-child {
  width: 251px;
}

tbody.scrollContent td {
  width: 233px;
}
<table cellspacing="0" cellpadding="0" class="scrollTable">
  <thead class="fixedHeader">
    <tr class="alternateRow">
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
  </thead>
  <tbody class="scrollContent">
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>And Repeat 1</td>
      <td>And Repeat 2</td>
      <td>And Repeat 3</td>
    </tr>
    <tr class="normalRow">
      <td>Cell Content 1</td>
      <td>Cell Content 2</td>
      <td>Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>More Cell Content 1</td>
      <td>More Cell Content 2</td>
      <td>More Cell Content 3</td>
    </tr>
    <tr class="normalRow">
      <td>Even More Cell Content 1</td>
      <td>Even More Cell Content 2</td>
      <td>Even More Cell Content 3</td>
    </tr>
    <tr class="alternateRow">
      <td>End of Cell Content 1</td>
      <td>End of Cell Content 2</td>
      <td>End of Cell Content 3</td>
    </tr>
  </tbody>
</table>
Culch answered 29/6, 2016 at 18:43 Comment(0)
D
0

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.

Defalcation answered 20/4, 2011 at 7:36 Comment(0)
P
0

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();
}
Philipps answered 16/5, 2013 at 17:26 Comment(2)
But in your demo the table header doesn't stay put, it just scrolls away. (Chrome here.)Eventual
I'm not seeing that in Chrome. Are you sure you're not mistaking the yellow highlighted cells with instructions in red for the header? The header cells are at the top and are gray on gray ("Col 1", "Col 2", etc.).Philipps
F
0

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.

Fonsie answered 26/7, 2016 at 13:34 Comment(0)
C
0

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...

Cobbs answered 23/1, 2019 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.