我有一个固定的嵌套元素,它是position:fixed。它的直接父对象是应用了转换转换transform : translate(2px,2px);的position:relative。
但由于此转换应用于父元素,因此嵌套的固定元素无法脱离父元素,而是相对于窗口定位自身
这是有意为之的行为还是可能是一个bug?它在chrome、safari和firefox上的表现也是一样的。
想知道如果相对父元素应用了转换,我如何将嵌套的固定元素拆分出来。
我附上的代码片段是我正在工作的实际代码的简化版本。
.fixed {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
font-size:30px;
background-color:beige;
}
.relative {
position:relative;
width:300px;
height: 300px;
background-color:skyblue;
font-size: 20px;
top : 100px; left: 100px;
/* this is causing the 'bug'*/
transform : translate(2px,2px);
}
.fixed-2 {
width:150px;
height:150px;
background-color:gray;
top: 0;
left : 0;
transform:translate(100px, 0px);
font-size:16px;
}<div class="fixed">
Fixed Element
<div class="relative">
Relative Element
<div class="fixed fixed-2">
Why is this fixed element position relative to its parent and not the window?
</div>
</div>
</div>
或者,我也可以用codepen来复制它。https://codepen.io/farisk/pen/zYvXvox
发布于 2020-05-25 14:01:21
基本上- fixed元素的位置将相对于第一个带relative规则的父元素,因此这是预期的。
我不确定为什么要使用transform来定位元素,也不确定您希望在更复杂的代码中得到什么结果,但是您可以从父级中删除relative,并将固定位置的左上角设置为您希望它所在的位置。
或者,只需添加固定的div作为body的子元素,这样您就不需要更改已有的其他元素的css。
.fixed {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
font-size:30px;
background-color:beige;
}
.relative {
width:300px;
height: 300px;
background-color:skyblue;
font-size: 20px;
top : 100px; left: 100px;
}
.fixed-2 {
width:150px;
height:150px;
background-color:gray;
top: 30px;
left : 30px;
font-size:16px;
}<div class="fixed">
Fixed Element
<div class="relative">
Relative Element
<div class="fixed fixed-2">
Why is this fixed element position relative to its parent and not the window?
</div>
</div>
</div>
https://stackoverflow.com/questions/61996570
复制相似问题