HTML Table overflow-y scrolling with fixed y axis headings

半腔热情 提交于 2019-12-11 02:48:52

问题


I have a table with headers for both the x and y axes, and want the table to scroll when it overflows on the y axis while retaining the header.

Using display: block; overflow-y: auto; in the <table> element gives me some scrolling, but I lose the y axis labels.

Here's a simple pen work-in-progress: https://codepen.io/Malgalin/pen/wNZRPz?editors=0100

I have also tried versions of making the th[scope='row'] elements have a fixed position, which sort of works, but it creates messy over-lapping headers and makes the initial blank top left corner cell disappear.

I'm happy to see answers using JS or jQuery if necessary.


回答1:


You can use the sticky position for your headers. You need to change your HTML a little bit, you need a wrapper for the table.

<div id='table_wrapper'>
  <table> .... </table>
</div>

Now you can set the TH elements to position: sticky and, for the thead, make it stick at top: 0px, for the tbody use left: 0px.

Using just that won't work on your actual code since you have some errors though. So, first close the thead tag and open a tbody tag properly (now you open the thead and close a tbody). The second thing you need to fix is to remove those display: block on the table elements, when you do that you break the table.

Check this edited codepen link https://codepen.io/anon/pen/daLrGZ?editors=1100

Note that you'll need to add some background to the th's.

EDIT: if you want the top left TH to stay over the rest THs add this:

table thead tr th:first-child {
  left: 0px; //so it also sticks to the left
  z-index: 2; //so it's over the rest
}



回答2:


Maybe what you are looking is already solved, have a look and let me know: https://stackoverflow.com/a/50649696/5796090

In the link above you can find a scrollable table with a fixed header using CSS Grid.

Basically you define 2 areas in your grid for thead and tbody and set an overflow for the second one.

table {
  display: inline-grid;
  grid-template-areas: 
  "head-fixed" 
  "body-scrollable";
}

thead {
  grid-area: head-fixed;
}

tbody {
  grid-area: body-scrollable;
  overflow: auto;
  height: 400px; /* define height depending on your needs */
}

Hope this help :)



来源:https://stackoverflow.com/questions/54797756/html-table-overflow-y-scrolling-with-fixed-y-axis-headings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!