为何设置position: fixed的元素会遵循父元素的margin属性?
为什么未设置top/left的fixed元素会跟着父元素的margin-left走?
先看两个对比示例:
示例1:未设置top/left的fixed元素
<div style="height: 100vh; background-color: lightblue; margin-left: 300px;"> <div style="position: fixed; background-color: tomato; width: 100px; height: 100px;"> </div> </div>
示例2:设置了top/left的fixed元素
<div style="height: 100vh; background-color: lightblue; margin-left: 300px;"> <div style="position: fixed; background-color: tomato; width: 100px; height: 100px; top: 0px; left: 0px;"> </div> </div>
核心原因:
- 当元素设置
position: fixed但未指定top/left/right/bottom时,浏览器会以它的静态位置作为定位基准——也就是这个元素如果用默认的position: static(正常流布局)时,原本该处于的位置。 - 父元素的
margin-left: 300px让父元素在正常流里向右偏移了300px,这个fixed子元素的静态位置就跟着父元素的布局位置走,所以看起来像是“遵循”了父元素的margin。 - 一旦明确设置
top: 0和left: 0,就直接指定了元素相对于视口左上角的定位规则,静态位置的参考逻辑被覆盖,元素就直接贴合视口边缘,不再受父元素布局影响。
内容的提问来源于stack exchange,提问作者Saravana Kumar
相关产品推荐
相关产品推荐

