Border style do not work with sticky position element

后端 未结 11 2281
攒了一身酷
攒了一身酷 2020-12-01 13:41

I don\'t know why my border style do not work with position: sticky; attribute. I would like to set border styles on my sticky table header. But I don\'t want t

11条回答
  •  醉梦人生
    2020-12-01 14:17

    Tried some of the existing answers, but as comments have mentioned, they result in a one pixel gap between the borders.

    Made a workaround, though it requires JavaScript. It places a

    in each , on resize it fits the
    to the . The border is then instead applied to the
    .

    Note that as of writing this, position: sticky is not working in Chromium on , it works in Firefox. However, the position: sticky related CSS does not affect the page, if the JavaScript is not executed.

    Click Run code snippet to see if it works, in your browser.

    function onResize() {
        $("thead th div").each(function () {
            var width = $(this).parent().outerWidth() - 2; // -2 * border-width
            $(this).css("width", width + "px");
        });
    }
    
    $("thead th").each(function () {
        $(this).append($("
    ")); }); $(window).on("resize", onResize); onResize();
    table {
        width: 100%;
        border-collapse: collapse;
    }
    
    th {
        text-align: left;
    }
    
    th, td {
        padding: 12px 20px;
    
        border: 1px solid rgba(0, 0, 0, 0.125);
    }
    
    table thead {
        position: sticky;
        top: 0;
    
        background: #FFF;
    }
    
    /* Used as a workaround for position: sticky not rendering the border */
    thead th div {
        width: 30px;
        margin: 0 -20px; /* -20px to negate the 20px from the padding */
        position: absolute;
        top: 0;
        bottom: 0;
        z-index: -1;
    
        border-right: 1px solid rgba(0, 0, 0, 0.125);
        border-bottom: 1px solid rgba(0, 0, 0, 0.125);
    }
    
    
    
    A B C D
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234
    1234

    Wrap the previous JavaScript in the following, to limit it to Firefox.

    if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
        // ...
    }
    

    Screenshot (Firefox 71):

提交回复
热议问题