Explain in detail how to solve the position: fixed fixed fixed positioning offset problem

Time:2021-11-28

problem

CSS fixed positioning position: fixed is easy to use, that is, positioning relative to the browser’s viewport, top: 0; Left: 0 is in the upper left corner.


<body>
  <div class="container">
  </div>    
</body>    
<style>
  .container{
    width: 100px;
    height: 100px;
    background: #888;
    position: fixed;
    top: 100px;
    left: 100px;
  }
</style>

When the parent element is set to transform


<body>
    <div class="BFC-box">
      <div class="container"></div>
    </div>
</body>
<style>
  .BFC-box{
    margin:200px;
    height: 200px;
    width: 200px;
    border:2px solid red;
    transform: scale(1);
  }
  .container{
    width: 100px;
    height: 100px;
    background: #888;
    position: fixed;
    top: 100px;
    left: 100px;
  }
</style>

The fixed element becomes positioned relative to the parent element.

It’s really painful because transform improves the status of elements. It is described in the W3C specification as follows:

For elements whose layout is governed by the CSS box model, any value other than none for the transform also causes the element to become a containing block, and the object acts as a containing block for fixed positioned descendants

In elements whose transform is not none, positioning will be affected.

Solution

Without affecting the layout, you can directly move the element to be located to the body:


<body>
  <div class="BFC-box"></div>
  <div class="container">
  </div>    
</body>    

If it is inconvenient to operate elements in components, JS can be used, taking Vue as an example:


<div ref="container" class="container"></div>
mounted(){
  document.body.append(this.$refs['contaier'])
}

This is the end of this article on how to solve the problem of position: fixed fixed fixed positioning offset. For more relevant position: fixed fixed positioning offset content, please search for previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!