How to make the wrapping div element with relative position match child elements height?

前端 未结 2 1418
名媛妹妹
名媛妹妹 2021-02-06 05:02

I have a simple problem where I have 2 divs, 1 is relative positioned. The child element is absolute positioned. This child has varying height.

The code so far:

相关标签:
2条回答
  • 2021-02-06 05:44

    No, you can't make a parent with position: relative adjust its height to fit a child element with position: absolute.

    This is because:

    In the absolute positioning model, a box is explicitly offset with respect to its containing block. It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes.

    http://www.w3.org/TR/CSS21/visuren.html#absolute-positioning

    If you wanted to stick with your position based code, you'd have to use JavaScript to set the height of the parent div.

    Otherwise, stick to using floats if they work for your case. @MatTheCat's answer looks good to me.

    Just for completeness, here's a demo of @MatTheCat's answer with height: 200px added, so you can see the parent div does adjust in height: http://jsfiddle.net/gR2wL/3/

    0 讨论(0)
  • 2021-02-06 05:58

    Absolute positionned elements are outside the flow so parents can't adjust their height.

    But you can simply use:

    #wrap {
        width: 100%; /* useless */
        background: #ccc;
        overflow:hidden; /* establish a new formatting context */
        min-height: 20px;
    }
    
    #inner {
        width:30%;
        background: #000;
        float:right;
    }
    
    0 讨论(0)
提交回复
热议问题