关于 absolute
定位,fixed
似乎像 relative
一样工作。
.fixed, .relative {
border: 1px solid;
width: 150px;
height: 150px;
}
.fixed {
border-color: red;
position: fixed;
}
.relative {
border-color: blue;
margin-left: 200px;
position: relative;
}
.absolute {
background-color: rgba(0, 0, 0, 0.2);
position: absolute;
}
.a {
top: 0;
left: 0;
}
.b {
bottom: 0;
right: 0;
}
<div class="fixed">
<span class="absolute a">Left Top</span>
<span class="absolute b">Right Bottom</span>
</div>
<div class="relative">
<span class="absolute a">Left Top</span>
<span class="absolute b">Right Bottom</span>
</div>
不幸的是,我不明白为什么。我希望这会在某处定义,但我只能找到讨论 absolute
和 relative
的资源,而不是 absolute
和 fixed
.
这引出了一个问题:关于 absolute
位置,我是否可以处理 fixed
和 relative
元素?同样,是否可以使用 top
/left
/right
/bottom
来控制到父级的偏移量?
最佳答案
我认为除了 position:static
之外的任何东西都会为定位的 child 设置一个新的父上下文。
这可以在 MDN 文档中针对绝对定位 进行验证
The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).
因此设置 position:fixed
确实会导致绝对子元素跟随新上下文。
这个可以看出来fiddle here .更改 .rel
div 的 position
会移动红色 div 的集合,但绝对定位的蓝色 div 会随之移动。
另一个很好的来源是 w3.org
An essential concept when it comes to absolute positioning is the containing block: the block box that the position and dimensions of the absolutely positioned box are relative to. For static boxes and relatively positioned boxes the containing block is the nearest block-level ancestor—the parent element in other words. For absolutely positioned elements however it’s a little more complicated. In this case the containing block is the nearest positioned ancestor. By “positioned” I mean an element whose position property is set to relative, absolute or fixed—in other words, anything except normal static elements.
关于CSS 定位 : Fixed and relative interchangeable regarding absolute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257964/