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