ILovemyPoncho ILovemyPoncho - 8 months ago 48
CSS Question

CSS scrollable table with fixed header, but using the browser scrollbar, not overflow

This is what I've done.

As you can see, when you use the browser scrollbar the whole table goes behind the "mainwrapper" div. I would like to have my table with a fixed header and I don't want to use overflow scroll.

What I tried was to simply assign a fixed position to thead.

position: fixed;

but then, the first row of the table takes the header place.

Is there a way to do that only with CSS? If not, what would be the best solution?

Answer Source

You can do this using CSS with javascript.

Basically, you use CSS to position the table and table header row, and to trick the table into behaving like divs. Then use javascript to manipulate the CSS positioning of the table header row and a "mask" div that hides the regular table rows as the table scrolls. Because your table now thinks it's divs and sizes the cells without matching them up in width, you also need to use CSS to set the widths so that the table header widths match the td widths.

The relevant components are:

<!-- divs with IDs are manipulated with javascript -->
<div class="fixedTableHolder">

  <div class="maskHolder">
     <div id="mask" class="mask">&nbsp;</mask>

  <div class="fixedTable">
    <div id="theTable" class="theTable">

       <!-- here is the table, header row must have an ID -->
       <table border="0" cellspacing="5" cellpadding="5"> 
          <tr id="thFixed" class="thFixed"> 
            <td class="col1">Header cell 1</td> 
            <td class="col1">regular cell</td>



It is fairly complex, and takes more than a minute or two to implement. I did it for an app where I was going to re-use it often. Here is a demo in jsFiddle (contains the CSS and javascript as well as html):