详解如何解决position:fixed固定定位偏移问题

发布时间:2022-04-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了详解如何解决position:fixed固定定位偏移问题脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_304_0@问题

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的元素中,定位是会受到影响的。

解决方案

不影响布局的情况下,可以直接把要定位的元素移动到body下:

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

如果是在组件中不方便对元素进行操作,可以使用js,以vue为例:

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

到此这篇关于详解如何解决position:fixed固定定位偏移问题的文章就介绍到这了,更多相关position:fixed固定定位偏移内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的详解如何解决position:fixed固定定位偏移问题全部内容,希望文章能够帮你解决详解如何解决position:fixed固定定位偏移问题所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。