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

问题

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

.container{

width: 100px;

height: 100px;

background: #888;

position: fixed;

top: 100px;

left: 100px;

}

c98c3b65ab311053d049cb083933a404.png

当父级元素设置transform之后

.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;

}

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

048f8bf2ff0591c72eeeecf72d4b9301.png

真是令人蛋疼,原因在于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下:

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

mounted(){

document.body.append(this.$refs['contaier'])

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值