子元素相对于视口的位置固定 [英] Child element positioned fixed relative to viewport
问题描述
是否有任何文档指定位置固定,相对或绝对位置或静态位置的元素的默认行为?
Is there any documentation that specifies what the default behaviour is for an element with position fixed, inside an element with position relative, absolute or static?
.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>
我自己的经验是,它相对于浏览器视口定位(除非使用了转换,或者在子代中省略了left / top),但是我如何证明这种情况应该总是这样呢?我如何知道是否有任何浏览器以不同的方式呈现此内容?也许相对于父对象定位孩子,或者根本不显示元素...
My own experiance is that it is positioned relative to the browser viewport (unless transform is used, or left/top is omitted in child), but how can i justify that this should always will be the case? How do i know if any browsers renders this differently? Perhaps positioning the child relative to the parent, or maybe not showing the element at all...
推荐答案
父对象的位置元素或任何祖先与 position:fixed
无关。来自规范:
The position of the parent element or any ancestor is irrelevant when it comes to position:fixed
. From the specification:
固定定位是绝对定位的子类别。唯一的区别是,对于固定位置的框,包含块是由视口建立的。
但是在某些特殊情况下,包含块可能会更改。使用过滤器
时会发生这种情况,例如我在这里说明, transform
像在此处解释,有时还会 will-change
(在此处解释)
But there is some special cases where the containing block can change. It happens when using filter
like I explained here, transform
like explained here and sometimes will-change
(explained here)
关于顶部/左侧/底部/右侧的使用,您需要考虑静态位置。如果您未设置任何这些值,则浏览器将考虑放置元素的静态位置。仍来自规范:
Concerning the use of top/left/bottom/right you need to consider the static position. If you don't set any of those values the browser will consider the static position to place the element. Still From 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
元素始终考虑视口作为其包含块(放置的参考),除非在上层使用了某些特殊属性(变换,过滤器等)。该元素的位置由顶部/左侧/右侧/底部定义,也可以由规范中描述的静态位置定义。
A position:fixed
element always consider the viewport as its containing block (the reference for its placement) unless there is some particular properties used in a upper level (transform, filter, etc). The position of that element is either defined by top/left/right/bottom or by the static position like described in the specification.
相关问题,以获取有关静态位置:为什么我绝对定位的元素没有位于我期望的位置?
Related question to get more details about the static position: Why aren't my absolutely-positioned elements located where I expect?
这篇关于子元素相对于视口的位置固定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!