CSS position absolute - next positioned element is body?

做~自己de王妃 提交于 2019-12-10 15:05:23

问题


Quoting from msdn:

"Object is positioned relative to parent element's position—or to the body object if its parent element is not positioned"

Lets say I set a div with certain dimension to bottom 0; and left: 0; it will not be positioned at the bottom of body but at bottom left of viewport. Also when giving body a margin - the div will still be at bottom left of viewport.

I know how to work with these properties but I am looking for reasoning. Is it not the body to which the absolute elem is positioned to when no other ancestor is positioned? Thanks!

Here is the fiddle: http://jsfiddle.net/picbig/0p6rgv8f/

HTML:

<div id="large_box_greater_than_viewport"></div>
<div id="absolute_cnt"></div>

CSS:

body{
    margin-left: 200px;
}
#large_box_greater_than_viewport{
    width: 900px;
    height: 10000px;
    background: red;
}
#absolute_cnt{
    position: absolute;
    width: 65%;
    bottom: 0;
    left: 0;
    height: 80px;
    background: rgba(0,0,0,.7);
}

回答1:


Absolutely positioned elements are positioned relative to their containing block.

fixed positioned elements respect to the initial containing block which takes the dimensions of the viewport.

Initial containing block

The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media.

And absolute positioned elements respect to their containing block which is established by the nearest ancestor with a position of anything other than static. i.e. fixed, absolute or relative.

The key point is:

If there is no such ancestor, the containing block is the initial containing block.

Therefore that absolute positioned element inside <body> won't be placed with the respect to the <body> itself, but to the initial containing block, i.e. the viewport.

http://www.w3.org/TR/CSS2/visudet.html#containing-block-details




回答2:


You need to set the position of the body:

body{
    margin-left: 200px;
    position:relative;
}



回答3:


I tried some patterns in various browsers, and you are right!

The object is not positioned relative to the body unless the body is positioned too!

If the body is not positioned, the object is positioned relative to the viewport.




回答4:


1). Yes you can give position absolute to tag, but you need to put that tag inside another tag with position relative.

2). Or you can do this with after before functionality.



来源:https://stackoverflow.com/questions/32652139/css-position-absolute-next-positioned-element-is-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!