How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

后端 未结 13 2198
攒了一身酷
攒了一身酷 2020-11-27 03:11

How can I create a table that has its first row and first column both locked, as in Excel, when you activate \'freeze panes\'? I need the table to both scroll horizontally

13条回答
  •  情歌与酒
    2020-11-27 03:57

    It's actually do-able without JavaScript, but using pure CSS + HTML with sticky position. Just add "position:sticky" to the cells you'd like to freeze.

    For building a table, you can either use or CSS grid, and this technique works on both of them.

    Here is an example formatting with table tag ( live demo here ):

     ...  ... 
    ...
    

    And here is an example with CSS Grid ( live demo here ):

    ...
    ...

    You probably will need to take care of the cells frozen both horizontally and vertically ( e.g., setting a z-index larger than others ) but it will be still CSS thing.

    I think the main drawback of this approach is, probably, the browser compatibility issue. Check Can I Use CSS-sticky and Can I use CSS grid before using these techniques.

提交回复
热议问题