相对于视口固定定位的子元素
Child element positioned fixed relative to viewport
是否有任何文档指定固定位置元素、相对位置元素、绝对位置元素或静态元素内的默认行为是什么?
.parent {
position: relative; /* or absolute/static */
height: 200px;
width: 200px;
top: 30px;
left: 50px;
background-color: red;
}
.child {
position: fixed;
height: 100px;
width: 100px;
left: 10px;
top: 20px;
background-color: blue;
}
<div class='parent'>
<div class='child'></div>
</div>
我自己的经验是它是相对于浏览器视口定位的(除非使用了转换,或者在 child 中省略了 left/top),但我如何证明这应该总是如此?我怎么知道是否有任何浏览器以不同方式呈现它?也许相对于父元素定位子元素,或者根本不显示该元素...
对于 position:fixed
,父元素或任何祖先元素的位置无关紧要。来自 the specification:
Fixed positioning is a subcategory of absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport.
但在某些特殊情况下,包含块可能会发生变化。当使用 filter
如 , transform
like explained here and sometimes will-change
()
时会发生这种情况
关于top/left/bottom/right的使用需要考虑静态位置。如果您不设置任何这些值,浏览器将考虑静态位置来放置元素。仍然来自 the specification:
For the purposes of this section and the next, the term "static position" (of an element) refers, roughly, to the position an element would have had in the normal flow. More precisely ...
A position:fixed
元素始终将视口视为其包含块(其放置的参考),除非在上层(转换、过滤器等)中使用了某些特定属性。该元素的位置由 top/left/right/bottom 或规范中描述的静态位置定义。
有关静态位置的更多详细信息的相关问题:
是否有任何文档指定固定位置元素、相对位置元素、绝对位置元素或静态元素内的默认行为是什么?
.parent {
position: relative; /* or absolute/static */
height: 200px;
width: 200px;
top: 30px;
left: 50px;
background-color: red;
}
.child {
position: fixed;
height: 100px;
width: 100px;
left: 10px;
top: 20px;
background-color: blue;
}
<div class='parent'>
<div class='child'></div>
</div>
我自己的经验是它是相对于浏览器视口定位的(除非使用了转换,或者在 child 中省略了 left/top),但我如何证明这应该总是如此?我怎么知道是否有任何浏览器以不同方式呈现它?也许相对于父元素定位子元素,或者根本不显示该元素...
对于 position:fixed
,父元素或任何祖先元素的位置无关紧要。来自 the specification:
Fixed positioning is a subcategory of absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport.
但在某些特殊情况下,包含块可能会发生变化。当使用 filter
如 transform
like explained here and sometimes will-change
(
关于top/left/bottom/right的使用需要考虑静态位置。如果您不设置任何这些值,浏览器将考虑静态位置来放置元素。仍然来自 the specification:
For the purposes of this section and the next, the term "static position" (of an element) refers, roughly, to the position an element would have had in the normal flow. More precisely ...
A position:fixed
元素始终将视口视为其包含块(其放置的参考),除非在上层(转换、过滤器等)中使用了某些特定属性。该元素的位置由 top/left/right/bottom 或规范中描述的静态位置定义。
有关静态位置的更多详细信息的相关问题: