Search code examples
htmlcsspositioningcss-position

Why is this absolutely positioned element not positioning relative to its container?


I have this simple code to place two div #container elements side by side. In each of these there is a child div #child which I would like to position relative to its parent (div #container).

<style>
.container {
    float:left;
    margin-right: 10px;
}

.child {
    position: absolute;
    left: 0.2ex;
}
</style>

<div class="container">a<br/>
    <div class="child">b</div>
</div>
<div class="container">c<br/>
    <div class="child">d</div>
</div>​

However, rather than the result I would expect - 'd' is positioned below 'c' but pushed slightly to the right, 'd' is instead positioned over 'b' and slightly to the right. In other words the absolute position has been rendered relative to the page rather than to its containing element.

  1. Why is this the case? What have I misunderstood about absolute positioning here?
  2. How can I get the behaviour I was expecting?

See this jsFiddle.


Solution

  • Absolutely positioned elements are positioned with respect to the edges of their containing block, which is defined as the first ancestor that is not position: static.

    None of the ancestor elements are position: static, so it is with respect to the initial position of the viewport.

    Set position: relative on the .container elements if you really want to absolutely position them.

    That said, it looks like you would be better off doing this instead:

    .child {
        margin-left: 0.2ex;
    }