关于前端:如何解决positionfixed固定定位偏移问题

2次阅读

共计 1007 个字符,预计需要花费 3 分钟才能阅读完成。

问题

css 固定定位 position:fixed 很容易应用,就是绝对浏览器的 viewport 进行定位,top:0;left:0就是在左上角。

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

当父级元素设置 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>

fixed 元素变成了绝对父元素进行定位。

真是令人蛋疼,起因在于 transform 晋升了元素的位置,在 W3C 标准中有如下阐明:

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

在 transform 不为 none 的元素中,定位是会受到影响的。

解决方案

  1. 在不影响布局的状况下,能够间接把要定位的元素挪动到 body 下:
<body>
  <div class="BFC-box"></div>
  <div class="container">
  </div>    
</body>    
  1. 如果是在组件中不不便对元素进行操作,能够应用 js,以 vue 为例:
<div ref="container" class="container"></div>
mounted(){document.body.append(this.$refs['contaier'])
}
正文完
 0