Search code examples
htmlcsscss-positionabsolute

Why is an absolutely positioned element placed by its sibling instead of at the top corner of the page?


I don't understand why my absolutely positioned element appears after my child_static div. I always thought that absolutely positioned elements are taken out of the flow. So why doesn't child_absolute cover the child_static div?

.parent {
    position: relative;
}
.child_static {
    height: 20px;
    background: blue;
}
.child_absolute {
    position: absolute;
    height: 20px;
    width: 100%;
    background: green;
}
<div class='parent'>
    <div class='child_static'></div>
    <div class='child_absolute'></div>
</div>

http://jsfiddle.net/4v4eLtp1/


Solution

  • I always thought that absolute positioned elements are out of the flow.

    Yes, they are removed from normal flow.

    I don't understand why absolute positioned element appeared after child_static div.

    Just because absolute positioning removes elements from normal flow, it doesn't mean it does alter the position of the elements as well.

    In other words, absolutely positioned elements would be at the same place as they are not positioned absolutely unless their top, left, ... offsets are set.

    So what happens is that they would overlap next sibling elements, because they are not part of document flow anymore.

    For instance have a look at the following example where the gold <div> element is covered by absolutely positioned element.

    .parent {
        position: relative;
    }
    
    .child_static {
        height: 20px;
        background: blue;
    }
    
    .child_absolute {
        position: absolute;
        height: 20px;
        width: 100%;
        background: green;
    }
    
    .child_static ~ .child_static {
        background: gold;
    }
    <div class='parent'>
        <div class='child_static'>Green</div>
        <div class='child_absolute'>Blue</div>
        <div class='child_static'>Gold</div>
    </div>