Solve the problem that the page will move horizontally when the scroll bar appears and disappears

Usually, when we look at some web pages, there is not much content at the beginning of loading, and there is no vertical scroll bar on the page. When we click to load more, the content height of the page exceeds one screen, so the scroll bar appears. At this time, the page will move horizontally to the left for a distance, which is just the width of the scroll bar, because the scroll bar occupies the original content display area After all, it's a very bad experience, so what's a good solution?
Here we can use the syntax of css3:
calc(): used for calculation, which is supported by IE9 + browser.
vw: the relative unit of the width of the browser window, which contains scroll bars
100%: this width is the width of the page content to the container, excluding the scroll bar
therefore:

.wrap-outer{
    margin-left: calc(100vw - 100%)
}

Self test

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
.wrap-outer{
    margin-left: calc(100vw - 100%)
}
</style>
<body>
    <button id='btn'>Change height</button>
    <div class='wrap-outer' >
     <div id='box' style="width:900px;margin:0 auto;height:500px;background: #999"></div> 
    </div>


</body>
<script>
    let len = true
    document.getElementById('btn').onclick = function() {
        if(len) {
           document.getElementById('box').style.height = '2000px' 
           len = !len
        } else {
           document.getElementById('box').style.height = '500px' 
           len = !len
        }

    }
</script>
</html>

Upgraded stability solution

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    html {
      overflow-y: scroll;
    }

    :root {
      overflow-y: auto;
      overflow-x: hidden;
    }

    :root body {
      position: absolute;
    }

    body {
      width: 100vw;
      overflow: hidden;
    }
</style>
<body>
    <button id='btn'>Change height</button>
    <div class='wrap' >
     <div id='box' style="width:900px;margin:0 auto;height:500px;background: #999"></div> 
    </div>


</body>
<script>
    let len = true
    document.getElementById('btn').onclick = function() {
        if(len) {
           document.getElementById('box').style.height = '2000px' 
           len = !len
        } else {
           document.getElementById('box').style.height = '500px' 
           len = !len
        }

    }
</script>
</html>

Tags: css3

Posted on Thu, 30 Apr 2020 04:56:28 -0700 by gere06