Table header to stay fixed at the top when user scrolls it out of view with jQuery

后端 未结 25 2143
悲&欢浪女
悲&欢浪女 2020-11-22 05:38

I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500

25条回答
  •  盖世英雄少女心
    2020-11-22 06:20

    I've tried most of these solutions, and eventually found (IMO) the best, modern, solution:

    CSS grids


    With CSS grids, you can define a 'grid', and you can finally create a nice, javascript-free, cross-browser solution for a table with a fixed header, and scrollable content. The header height can even dynamic.

    CSS: Display as grid, and set the number of template-rows:

    .grid {
        display: grid;
        grid-template-rows: 50px auto; // For fixed height header
        grid-template-rows: auto auto; // For dynamic height header
    }
    

    HTML: Create a grid container and the number of defined rows:


    Here is working example:

    CSS

    body {
      margin: 0px;
      padding: 0px;
      text-align: center;
    }
    
    .table {
      width: 100%;
      height: 100%;
      display: grid;
      grid-template-rows: 50px auto;
    }
    .table-heading {
      background-color: #ffffd;
    }
    .table-content {
      overflow-x: hidden;
      overflow-y: scroll;
    }
    

    HTML

    
        
        
        
            
    HEADING
    CONTENT - CONTENT - CONTENT
    CONTENT - CONTENT - CONTENT
    CONTENT - CONTENT - CONTENT
    CONTENT - CONTENT - CONTENT
    CONTENT - CONTENT - CONTENT
    CONTENT - CONTENT - CONTENT

提交回复
热议问题