开发者

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

开发者 https://www.devze.com 2023-03-12 21:09 出处:网络
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.

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:

HTML

<div id="wrap"><div id="inner"></div></div>

CSS

#wrap {
    width: 100%;
    background: #ccc;
    position: relative;
    min-height: 20px;
}

#inner {
    width:30%;
    background: #000;
    position: absolute;
    right: 0;
    top: 0;
    height: 200px;
}

The problem I have is that the #wrap element doesn't adjust its height to match the child element and开发者_Go百科 therefor the child element hangs outside the edge of the parent. Can this be done with relative and absolute positioned elements?

I know this can be achieved with floating elements and following them with css => cleared: both, but I'd like to know if its possible with this method.

I've created a jsfiddle of this problem over here if anybody would like to help me out!

Thanks a lot.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消