Skip to content
Advertisement

HTML table with fixed header and footer and scrollable body without fixed widths

I want to to create a table with fixed thead and tfoot and a scrollable tbody!

I’ve tried several approaches, both CSS only and CSS + Javascript, but they are all weak and unreliable and I can easily break them by changing the markup in the demo.

What I want is a way to have the table to behave like a table, this means that the browser will automatically adjust columns based on the content (both at page load that in case of window resize) and that in these scenarios:

  1. if the content of the column’s header (thead > tr > th) is larger than the content of the column’s body (tbody > tr > td) and larger than the content of the column’s footer (tfoot > tr > td) the column should resize based on the size of the column’s header

  2. if the content of the column’s body (tbody > tr > td) is larger than the content of the column’s header (thead > tr > th) and larger than the content of the column’s footer (tfoot > tr > td) the column should resize based on the size of the column’s body

  3. if the content of the column’s footer (tfoot > tr > td) is larger than the content of the column’s header (thead > tr > th) and larger than the content of the column’s body (tbody > tr > td) the column should resize based on the size of the column’s footer

The table below should clarify the scenarios:

JavaScript

I want a clean (as possible) and reliable solution that will work for the different scenarios, possibly CSS only but also JavaScript is OK (vanilla and clean JavaScript, not jQuery plugins). I don’t care about old browser support (it would be great to have it or at least to reach a solution which can degrade gracefully on old browser but it’s optional)… I can even accept to use divs instead of table nodes if the final solution works as expected… so in 2016, with modern browser and CSS is this possible somehow?!

EDIT:

The body should scroll vertically and the table may have any number of columns

UPDATE:

I came up with this solution: https://codepen.io/daveoncode/pen/LNomBE but I’m still not 100% satisfied. The main issue is that I can’t set different backgrounds for header and footer cells.

UPDATE 2:

it works now!

Advertisement

Answer

I finally implemented a working solution!

The relevant CSS is the following:

JavaScript

And this is the markup:

JavaScript

It works on Chrome, Firefox, Safari and IE11 (I don’t know how it behaves on older browsers). See it on codepen: https://codepen.io/daveoncode/pen/LNomBE

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement