固定的元素不能脱离已转换的相对父元素

问题描述 投票:0回答:1

我有一个固定的嵌套元素是 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中复制了这段代码。https:/codepen.iofariskpenzYvXvox。

html css css-position
1个回答
-1
投票

基本上 - 一个元素的位置 fixed 元素将相对于第一个父元素,并以 relative 规则,所以这是预料之中的。

不知道你为什么要用transform来定位元素,也不知道你在更复杂的代码中想要的结果是什么,但你可以去掉那个 relative 的父元素,并将固定位置的topleft设置在你想要的位置。

或者,只需将固定的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>
© www.soinside.com 2019 - 2024. All rights reserved.