htmlcsshtml-tablesticky

table with sticky header and horizontal scroll


I want a table with sticky header and horizontal scroll.

I dont want a vertical scroll inside the table. It should scroll with the page. So no set height of the table. Is this even possible?

Here is codepen of not working example: https://codepen.io/fwitkowski/pen/zYEQvvg

When I remove overflow: auto from table-container, position sticky works just fine.

.table-container {
  max-width:350px;
  overflow-x:auto; /* for horizontal scroll */
  position: relative; /* relative to the normal flow */
  border: solid 5px red /* for reference */
}

Solution

  • As per the MDN documentation:

    a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor.

    There's an active GitHub issue discussing this on the W3C repo, which has been running since 2017. There have been various workarounds suggested, but they all seem to rely on adding a fixed height to the table / table container, or using Javascript as in this answer.

    At least for the moment, this is not something that's supported natively.