Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto height on parent container with Absolute/Fixed Children

Im trying to set an automatic height a div that contains 2 child elements, positioned fixed and absolutely respecitvely.

I want my parent container to have an auto height but I know this is hard as the child elements are taken out of the page structure with their positions.

I have tried setting a height to my parent div that works, but with my layout being responsive, when its scaled down to mobile, the height remains the same where as the content within becomes stacked and so the height needs to increase with its children.

Not sure if this makes sense, I dont have my actual code on me atm but ive made a fiddle trying to explain...

http://jsfiddle.net/dPCky/

like image 953
Liam Avatar asked Jan 30 '12 09:01

Liam


2 Answers

The parent div can not use height:auto when its children are positioned absolute / fixed.

You would need to use JavaScript to achieve this.

An example in jQuery:

var biggestHeight = 0; // Loop through elements children to find & set the biggest height $(".container *").each(function(){  // If this elements height is bigger than the biggestHeight  if ($(this).height() > biggestHeight ) {    // Set the biggestHeight to this Height    biggestHeight = $(this).height();  } });  // Set the container height $(".container").height(biggestHeight); 

Working example http://jsfiddle.net/blowsie/dPCky/1/

like image 182
Blowsie Avatar answered Oct 17 '22 05:10

Blowsie


http://jsfiddle.net/dPCky/32/ - A similar effect using float:left;

http://jsfiddle.net/dPCky/40/ - An even closer result to your desired effect.

If you're willing to change your html, then you could do what I have done above.

I learned positioning from the following tutorials which I would highly recommend to anyone who wants to become a positioning pro in html/css:

http://www.barelyfitz.com/screencast/html-training/css/positioning/

I would generally avoid using javascript where possible when doing something that could potentially have a css or html level fix, if you're willing to adjust your html.

like image 45
Anicho Avatar answered Oct 17 '22 05:10

Anicho