Table fixed header and scrollable body

前端 未结 29 1687
粉色の甜心
粉色の甜心 2020-11-22 05:33

I am trying to make a table with fixed header and a scrollable content using the bootstrap 3 table. Unfortunately the solutions I have found does not work with bootstrap or

29条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 05:50

    Fixed table head - CSS-only

    Simply position: sticky; top: 0; your th elements. (Chrome, FF, Edge)

    .tableFixHead          { overflow-y: auto; height: 100px; }
    .tableFixHead thead th { position: sticky; top: 0; }
    
    /* Just common table stuff. Really. */
    table  { border-collapse: collapse; width: 100%; }
    th, td { padding: 8px 16px; }
    th     { background:#eee; }
    TH 1TH 2
    A1A2
    B1B2
    C1C2
    D1D2
    E1E2

    TH borders problem fix

    Since border cannot be painted properly on a translated TH element, to recreate and render "borders" use the box-shadow property:

    /* Borders (if you need them) */
    .tableFixHead,
    .tableFixHead td {
      box-shadow: inset 1px -1px #000;
    }
    .tableFixHead th {
      box-shadow: inset 1px 1px #000, 0 1px #000;
    }
    

    .tableFixHead          { overflow-y: auto; height: 100px; }
    .tableFixHead thead th { position: sticky; top: 0; }
    
    /* Just common table stuff. Really. */
    table  { border-collapse: collapse; width: 100%; }
    th, td { padding: 8px 16px; }
    th     { background:#eee; }
    
    /* Borders (if you need them) */
    .tableFixHead,
    .tableFixHead td {
      box-shadow: inset 1px -1px #000;
    }
    .tableFixHead th {
      box-shadow: inset 1px 1px #000, 0 1px #000;
    }
    TH 1TH 2
    A1A2
    B1B2
    C1C2
    D1D2
    E1E2


    Fixed table head - using JS. (IE)

    You can use a bit of JS and translateY the th elements

    jQuery example

    var $th = $('.tableFixHead').find('thead th')
    $('.tableFixHead').on('scroll', function() {
      $th.css('transform', 'translateY('+ this.scrollTop +'px)');
    });
    .tableFixHead { overflow-y: auto; height: 100px; }
    
    /* Just common table stuff. */
    table  { border-collapse: collapse; width: 100%; }
    th, td { padding: 8px 16px; }
    th     { background:#eee; }
    TH 1TH 2
    A1A2
    B1B2
    C1C2
    D1D2
    E1E2

    Or plain ES6 if you prefer (no jQuery required):

    // Fix table head
    function tableFixHead (e) {
        const el = e.target,
              sT = el.scrollTop;
        el.querySelectorAll("thead th").forEach(th => 
          th.style.transform = `translateY(${sT}px)`
        );
    }
    document.querySelectorAll(".tableFixHead").forEach(el => 
        el.addEventListener("scroll", tableFixHead)
    );
    

提交回复
热议问题