广告位联系
返回顶部
分享到

解决position:fixed固定定位偏移问题的教程

css 来源:转载 作者:秩名 发布时间:2021-01-18 10:29:49 人浏览
摘要

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

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'])
}
 


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://www.jb51.net/css/759394.html
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计