Search code examples
htmlcsspositioncss-position

Why absolute parent get child height while relative parent doesn't?


I observed the behaviour that absolutely positioned parent will set its own height to cover child elements, while relatively positioned parent doesn't. I have created 2 jsfiddles to emulate this:

Absolute: https://jsfiddle.net/kc1g7v9s/

Relative: https://jsfiddle.net/smy5q8Ld/

When inspect element on rendered result, the absolute-container div's dimension is 220x60, whereas relative-container div's dimension is 689x0.

Why so? I'm not particularly trying to achieve anything, just curious on the behaviour.

Code attached:

Absolute:

<div class="absolute-container">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

.child1, .child2 {
    width: 100px;
    height: 60px;
    background-color: grey;
    margin-right: 10px;
}
.child1 {
    float: left;
}

.child2 {
    float: right;
}

.absolute-container {
    position: absolute;
    clear: both;
}

Relative:

<div class="relative-container">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

.child1, .child2 {
    width: 100px;
    height: 60px;
    background-color: grey;
    margin-right: 10px;
}
.child1 {
    float: left;
}

.child2 {
    float: right;
}

.relative-container {
    position: relative;
    clear: both;
}

Solution

  • That's because, as explained in this answer, floats are ignored when calculating the height of "normal" blocks:

    Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored […])

    enter image description here

    And position: relative does not change this.

    However, position: absolute produces a Block Formatting Context. For those,

    If the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges.

    enter image description here