首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修复了元素未脱离转换后的相对父元素的问题

修复了元素未脱离转换后的相对父元素的问题
EN

Stack Overflow用户
提问于 2020-05-25 13:55:18
回答 1查看 254关注 0票数 1

我有一个固定的嵌套元素,它是position:fixed。它的直接父对象是应用了转换转换transform : translate(2px,2px);的position:relative

但由于此转换应用于父元素,因此嵌套的固定元素无法脱离父元素,而是相对于窗口定位自身

这是有意为之的行为还是可能是一个bug?它在chrome、safari和firefox上的表现也是一样的。

想知道如果相对父元素应用了转换,我如何将嵌套的固定元素拆分出来。

我附上的代码片段是我正在工作的实际代码的简化版本。

代码语言:javascript
复制
.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;
}
代码语言:javascript
复制
<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

EN

回答 1

Stack Overflow用户

发布于 2020-05-25 14:01:21

基本上- fixed元素的位置将相对于第一个带relative规则的父元素,因此这是预期的。

我不确定为什么要使用transform来定位元素,也不确定您希望在更复杂的代码中得到什么结果,但是您可以从父级中删除relative,并将固定位置的左上角设置为您希望它所在的位置。

或者,只需添加固定的div作为body的子元素,这样您就不需要更改已有的其他元素的css。

代码语言:javascript
复制
.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;
}
代码语言:javascript
复制
<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>

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61996570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档