Problem description

Fixed positioning as opposed to viewport positioning, if you have a div element above you, when fixed positioning is turned on, the div is removed from the flow of the document (” floating away “), and the position occupied by the original div is vacated, causing the underlying div element to jump up. It can lead to layout disorder. The solution is simply to add a div to occupy the position of the element that turns on the fixed positioning. This div can be a sibling div (add it below) or a parent div (add another layer). However, the width and height of the new placeholder div must be the same as the width and height of the element that enabled the fixation. That’s the way it looks.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        .top{
            width: 100%;
            height: 80px;
            background-color: #baf;
            position: fixed;
        }
        .bottom {
            width: 100%;
            height: 100px;
            background-color: #faf;
        }
        .fatherDiv {
            width: 100%;
            height: 80px;
        }
        .brotherDiv {
            width: 100%;
            height: 80px;
        }
    </style>
</head>
<body>
    <! Add a parent div to hold the position -->
    <div class="fatherDiv">
        <div class="top"></div>
    </div>
    <! <div class="brotherDiv"></div>
    <div class="bottom"></div>
</body>
</html>
Copy the code

conclusion

The solution is simple. In fact, there is another idea (but wrong), is to do a JS to listen to the browser scroll bar event, when the browser scroll, div fixed position, do not start positioning, when the browser stopped, unfixed position. Seems to have solved the problem. But aside from the performance cost of using JS, it’s easier to listen for scrolling in the browser. However, it is difficult to determine when the browser has stopped scrolling, and if the browser has stopped scrolling, you will lose the scrolling effect, and so on. This method, WHICH I tried on my own, was very troublesome and failed to solve the problem. So the optimal solution is to use one of the above methods.