为什么CSS固定位置不只考虑视口? [英] Why Doesn't CSS Fixed Positioning Consider the Viewport Only?
问题描述
据我了解,CSS固定位置元素仅相对于视口。但是,据我所知,这是正确的,只是如果未指定 left,则它不会默认为0,而是默认为容器的左边缘-在本例中为main div。
HTML:
It's my understanding that a CSS fixed position element is relative to the viewport only. However, from what I can tell, this is true except that if "left" is unspecified, it doesn't default to 0 but rather to the left edge of what would have otherwise been its container - in this case, the main div. The HTML:
<div id="main">
<div id="fixed"></div>
<div id="content"></div>
</div >
CSS:
#main{
width:80%;
margin-left:auto;
margin-right:auto;
}
#fixed{
position:fixed;
width:100%;
height:25px;
background:yellow;
}
#content{
width 100%;
height:300px;
background:red
}
在 http://jsfiddle.net/2dudX/99/ 。如果我指定left:0,则固定元素将沿着屏幕的宽度移动。是什么原因导致这种现象?如果我未指定左侧,右侧,顶部或底部,则默认值是什么?
demonstrated at http://jsfiddle.net/2dudX/99/ . If I specify left:0 the fixed element will run the width of the screen. What causes this behavior? What are the defaults if I don't specify a left, right, top or bottom?
推荐答案
您看到的行为是正确的。
The behavior that you are seeing is correct.
如果将位置
属性设置为绝对
或 fixed
,并且未指定偏移量,则将元素定位到静态位置,即使用<$ c $时的位置c> position:static 。
If you set position
property to a value of absolute
or fixed
, and the offsets are not specified, then the element is positioned to the static position, that is, the position it would take with position: static
.
但是,区别是位置为绝对/固定的元素将从正常文档流中取出,而与偏移值(自动或明确指定)。
However, the difference is that the element with position absolute/fixed is taken out of normal document flow regardless of the offset values (auto or explicitly specified).
参考: http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width
具体来说,(我的释义部分):
Specifically, the section around (my paraphrase):
如果 left和 right为自动和宽度不是自动,然后将左设置为静态位置,然后求解正确
if 'left' and 'right' are 'auto' and 'width' is not 'auto', then set 'left' to the static position and then solve for 'right'
如果您想了解偏移量对高度的影响,请参见以下内容:
http:// www。 w3.org/TR/CSS2/visudet.html#abs-non-replaced-height
If you want to understand how height is affected by the offsets, see the following:
http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-height
这篇关于为什么CSS固定位置不只考虑视口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!