Prevent 100vw from creating horizontal scroll

前端 未结 11 2063
不知归路
不知归路 2020-12-04 19:13

If an element is set to width: 100vw; and there is a vertical scrollbar the width of the element will be equal to the viewport plus the width of the scrollbar.<

11条回答
  •  执笔经年
    2020-12-04 19:53

    I was also struggling with this, and I also thought of CSS variables as the solution. CSS variables aren't supported in IE11 though so I tried something else:

    I fixed it by calculating the width of the scroll bar: subtracting the width of the body (not including scroll bar) from the width of the window (including the scroll bar). I use this to add it to the 100% of the body, see plusScrollBar variable.

    JS:

        // calculate width of scrollbar and add it as inline-style to the body
    var checkScrollBars = function() {
        var b = $('body');
        var normalw = 0;
        var scrollw = 0;
        normalw = window.innerWidth;
        scrollw = normalw - b.width();
    
        var plusScrollBar = 'calc(' + '100% + ' + scrollw + 'px)'
        document.querySelector('body').style.minWidth = plusScrollBar;
    }();
    

    CSS:

    html{
        overflow-x: hidden;
    }
    

    Why I like this: it takes in consideration that not all scrollbars are the same width or considered as conserved space at all. :)

提交回复
热议问题