Html 绝对定位与百分比给出意想不到的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9404603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute positioning with percentages giving unexpected results
提问by Jeroen
Please consider this jsfiddle, containing this html code:
请考虑这个 jsfiddle,包含这个 html 代码:
<div id="container">
<div id="item">TEST</div>
</div>
And some CSS:
还有一些CSS:
#container {
border: 1px solid red;
height: 100px;
width: 100px;
}
#item {
border: 1px dashed purple;
position: absolute;
left: 50%;
}
The results surprise me. Looking at the W3 positioning propsI'd expect the #item
to have its left value at 50% of the "containing block": the #container
. However, it seems to be at 50% of the entire page, not just the containing block. Even more surprising: if I tell the overflow of the container to stay hidden the "TEST" will still be there.
结果令我吃惊。看看W3 定位道具,我希望#item
它的左值位于“包含块”的 50% 处:#container
. 但是,它似乎占整个页面的 50%,而不仅仅是包含块。更令人惊讶的是:如果我告诉容器的溢出保持隐藏状态,“测试”仍然存在。
All major browsers (including IE9) seem to exhibit the same behavior, so my expectations are probably incorrect. The question then is: what part of the spec explains this behavior, if any?
所有主要浏览器(包括 IE9)似乎都表现出相同的行为,所以我的期望可能是不正确的。那么问题是:规范的哪一部分解释了这种行为,如果有的话?
回答by animuson
The absolute positioning is applied relative to the next parent element whose position is not static. In your case, that's the full page. Try setting position: relative
on the container division.
See the jsFiddle.
绝对定位是相对于位置不是静态的下一个父元素应用的。在你的情况下,那是整页。尝试设置position: relative
容器分区。
请参阅 jsFiddle。
回答by mohsen dorparasti
add
添加
position:relative;
to container div .
到容器 div 。
回答by thepriebe
When giving an element absolute position you take it out of the normal flow of the document. Absolute is the very upper left portion of the screen regardless of the other elements in the page. So by saying left: 50% you're saying half way in from the absolute left of the screen.
当给一个元素绝对位置时,你把它从文档的正常流中取出。绝对是屏幕左上角的部分,与页面中的其他元素无关。所以说 left: 50% 你说的是从屏幕绝对左边的一半。