0

I am building a html table with > 100 rows, for what I'd like the table head to stay visible. The user should have the possibility to resize the cells via mouse click in the frontend; As seen here.

I've tried to use display: block to fix the first row. But when I use JavaScript to resize the table, all th from thead show up within width of first column of tbody. It's probably related to the absolut-position in JS.

table thead tr {
    display: block;
    position: relative;
}

table tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 200px;
}

For now users can only adjust size of th, which is per default shrinked to the width of first column from tbody. I'd like the user to click anywhere in the table to change the whole column-width, th and td; the first row (thead) has to be always fixed and visible.

Jonas
  • 111
  • 2
  • 13
  • `display block` will break your display because tables use `display: table`. I can almost get it to work giving the thead `position: fixed` but that breaks how the table layout is calculated – Matt Ellen Aug 05 '19 at 13:19
  • Possible duplicate of [Table with fixed header and fixed column on pure css](https://stackoverflow.com/questions/15811653/table-with-fixed-header-and-fixed-column-on-pure-css) – Matt Ellen Aug 05 '19 at 13:37

1 Answers1

0

I've found a solution on Google:

Now, I've wrapped the table into another div and added following JS

document.getElementById("myDiv").addEventListener("scroll",function(){
   var translate = "translate(0,"+this.scrollTop+"px)";
   this.querySelector("thead").style.transform = translate;
});

Set the div properties to overflow: auto; background-color: white; and you're good to go!

Jonas
  • 111
  • 2
  • 13
  • 1
    The `scroll` event gets called very frequently. It would be better to cache the `thead` element outside the event callback. Reduces the `querySelector` calls to a minimum and helps performance. – Armin Bu Aug 05 '19 at 14:35