我有一个固定的嵌套元素,它是position:fixed
。它的直接父级是position:relative
,翻译转换为transform : translate(2px,2px)
;应用于它。
但是由于此转换已应用于父对象,因此嵌套的固定元素无法脱离父对象,而无法相对于窗口定位自身
这是预期的行为还是错误?在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中。 Python documentation
答案 0 :(得分:-1)
基本上-mvn quarkus:dev
元素的位置将相对于具有fixed
规则的第一个父元素,因此这是预期的。
不确定为什么要使用transform来定位元素,也不确定要在更复杂的代码中得到什么结果,但是可以从父级中删除relative
并设置固定位置的顶部/左侧您想要的位置。
或者,只需将固定div添加为主体的子代,这样就无需更改已经具有的其他元素的css。
relative
.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;
}