Reputation: 11240
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 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.
Upvotes: 8
Views: 21649
Reputation: 228162
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 float
s 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/
Upvotes: 10
Reputation: 18721
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;
}
Upvotes: 12