南强小屋 Design By 杰米

问题

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>

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

当父级元素设置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元素变成了相对父元素进行定位。

详解如何解决position: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,定位偏移

南强小屋 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
南强小屋 Design By 杰米

评论“详解如何解决position:fixed固定定位偏移问题”

暂无详解如何解决position:fixed固定定位偏移问题的评论...

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。