Search code examples
csspositionabsolute

CSS position absolute - next positioned element is body?


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);
}

Solution

  • 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