相对于充当相对父元素的 CSS 位置绝对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14384365/
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
CSS Position Absolute With Respect to a Parent Element Acting as Relative
提问by brooklynsweb
In my long journey to update my CSS skills from the deprecated dust that they have turned into, I've been playing around with certain CSS properties —particularly z-index —I'm noticing something strange or maybe there's a certain condition.
在我从废弃的 CSS 技能中更新我的 CSS 技能的漫长旅程中,我一直在玩弄某些 CSS 属性——尤其是 z-index——我注意到一些奇怪的东西,或者可能存在某种情况。
Example: http://jsfiddle.net/mEpgR/
示例:http: //jsfiddle.net/mEpgR/
The element div1's parent is cont, I've made div1's position property set to absolute, yet when I shift it, it's moving relative to its parent. I was under the impression that items set to absolute positioning are outsider regular flow and move only relative to browser port as their parent.
元素 div1 的父元素是 cont,我已经将 div1 的位置属性设置为绝对,但是当我移动它时,它相对于它的父元素移动。我的印象是,设置为绝对定位的项目是外部常规流,并且仅相对于浏览器端口作为其父项移动。
What am I missing?
我错过了什么?
If the fiddle link does not work, code:
如果小提琴链接不起作用,请编码:
CSS:
CSS:
.cont {
position:relative;
height:200px;
top:200px;
left:100px;
background: green; width: 200px;
}
.div1 {
background:red;
position:absolute;
top:50px;
}
HTML:
HTML:
<div class="cont">
<div class="div1">DIV1</div>
</div>
回答by Mike Brant
An absolute positioned element is positioned relative to the first parent element that has a position other than static. Since you have it inside a parent with relative
it will be absolutely positioned relative to this parent.
绝对定位元素相对于具有非静态位置的第一个父元素进行定位。由于您在父级中拥有relative
它,因此它将相对于该父级绝对定位。
You might be looking for fixed
position, which is relative to browser window.
您可能正在寻找fixed
相对于浏览器窗口的位置。