Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table header needs to remain fixed during scrolling [duplicate]

I have a table with a header and a body, and I want the table header to remain fixed while scrolling happens on the body.

The table is set up like so:

<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>

        ...more rows for data...

    </tbody>

The table is encapsulated with a and has CSS like:

overflow-x: hidden;
overflow-y: auto;
height: 400px;

I need the table header to remain perfectly still but when I add position: fixed; to thead or to the individual th the header gets squished.

Whats the best approach for this?

like image 253
cdub Avatar asked Sep 05 '13 19:09

cdub


2 Answers

i just updated a plugin that I wrote that does this exact thing:

http://mkoryak.github.io/floatThead/

it may be what you need

like image 192
mkoryak Avatar answered Sep 20 '22 16:09

mkoryak


If you need your tables to contain any dynamic data so that you can't specify width, you'll have to use a JS/jQuery solution like the following:

Table header to stay fixed at the top when user scrolls it out of view with jQuery

If you know exactly what is going to be displayed though and don't mind making some tweaks/hacks, you can just make your thead position:fixed, then mess with the spacing until it looks good.

Take a look at this jsFiddle to see what I mean.

EDIT: Here's an updated jsFiddle that's spaced a little better, because OP was too lazy to type in a few characters for himself and expects others to do everything for him.

http://jsfiddle.net/yXTD9/1/

like image 38
Jason Avatar answered Sep 17 '22 16:09

Jason