Search code examples
csswebstylesheetfixed-header-tables

Fixing table header on webpage


I would like to know how to fix a table header even if we scroll down on a website and out of the table view. I would like to use css style to do this. Thank you.

I would also like to know how to fix an element on a webpage so it always appears even when we scroll down. The image can be text. Use div and css


Solution

  • Taken from an old post of mine, here's an example of both things that you want done together in one fiddle.

    JSFiddle

    JQuery:

    function moveScroll() {
    
    var scroll = $('#table-container').offset().top;
    var anchor_top = $("#maintable").offset().top;
    var anchor_bottom = $("#bottom_anchor").offset().top;
    
    if (scroll > anchor_top && scroll < anchor_bottom) {
    
    clone_table = $("#clone");
    
    if (clone_table.length === 0) {
    clone_table = $("#maintable").clone();
    clone_table.attr({
        id: "clone"
    }).css({
        position: "fixed",
        "pointer-events": "none",
        left: $("#maintable").offset().left + 'px',
        top: 130
    }).width($("#maintable").width());
    
    $("#table-container").append(clone_table);
    
    $("#clone").width($("#maintable").width());
    
    $("#clone thead").css({
        visibility: "true"
    });
    
    $("#clone tbody").css({
        visibility: "hidden"
    });
    
    var footEl = $("#clone tfoot");
    if (footEl.length) {
    footEl.css({
        visibility: "hidden"
    });
    }
    }
    } else {
    $("#clone").remove();
    }
    }
    
    $('#table-container').scroll(moveScroll);