is there a way to auto adjust container DIV height to accommodate absolutely positioned child DIVs? i'd like to get something like
+-----------------------+ | container | | +------+ +------+ | | | chld | | chld | | | | 1 | | 2 | | | | | | | | | +------+ +------+ | | +------+ | | | chld | | | | 3 | | | | | | | +------+ | +-----------------------+
i try something like:
<div class="container" style="position: relative; border: solid thin"> <div class="chld" style="width: 20px; height: 20px; position: absolute; left: 5px; top: 5px; border: dashed thin;"><div> <div class="chld" style="width: 20px; height: 20px; position: absolute; left: 30px; top: 5px; border: dashed thin;"><div> <div class="chld" style="width: 20px; height: 20px; position: absolute; left: 15px; top: 30px; border: dashed thin;"></div> </div>
but the "container" div stays zero height. I understand, that this might be the expected behaviour, as elements are 'taken out' of the flow when positioned absolutely, but is there a workaround for this? (except for precalculating the resulting height and setting it manually)
If height: auto; the element will automatically adjust its height to allow its content to be displayed correctly. If height is set to a numeric value (like pixels, (r)em, percentages) then if the content does not fit within the specified height, it will overflow.
Centering div (vertical/horizontally)Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
If you use position:relative instead of position absolute an empty space will stay in the page structure where the element should be, and this space will be the height of the element you've moved.
So you could float chld1 and chld2 to get them side by side, add top & bottom padding to push chld 3 down and use position relative to split them apart and move to any height. Then use clear both on chld3.
Something like
#exp_outer { width: 400px; border: 1px solid black; } #chld1 { float: left; margin: 30px 0 20px; left: 50px } #chld2 { float: right; margin: 30px 0 20px; right: 50px; } #chld3 { left: 150px; clear: both; } .box { position: relative; width: 80px; height: 80px; border: 1px solid black; }
<div id="exp_outer"> <div id="chld1" class="box">Child1</div> <div id="chld2" class="box">Child2</div> <div id="chld3" class="box">Child3</div> </div>
overflow:auto
This is the new clearfix method, FYI. However, it doesn't always expand the container to the height of its tallest & absolutely positioned child.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With