0

http://jsfiddle.net/nWb5j/68/

Hi there! As you can see in the jsfiddle above, I have a parent div that has a position of relative with child divs with position of absolute.

<div class="d1">
  <div class="d2">W<br>o<br>r<br>l<br>d
  </div>
  <div class="d3">Hello</div>
</div>

d1 has a position of relative, while d2 and d3 have positions of absolute.

I have tried the following jQuery to no success:

$('.d1').css(height,($( "d3" ).height());

(As you can probably tell, I have no clue what I'm doing.)

I would like for the parent div to have the height of whatever the tallest child is, if possible. If that doesnt work, then to have the parent the same height as one of the children would work too.

I am very new to jQuery and javascript and have tried a few things, but none of them seem to work.

Thanks in advance!

  • Why are you using absolute positioning of the child elements? What is the final layout suppose to look like? – Marc Audet Oct 05 '14 at 17:14
  • The final result is a tabbed look so that the user can switch between the two divs to make one display on top of the other. That currently works, but because the parent element is positioned how it is, it messes with the page flow. – user3368798 Oct 05 '14 at 17:42

4 Answers4

1

Possible duplicate of Auto height on parent container with Absolute/Fixed Children

So your answer would be: The parent div can not use "height:auto" when its children are positioned absolute / fixed.

You would need to use JavaScript to achieve this.

In jquery something like.

var biggestHeight = "0";
// Loop through elements children to find & set the biggest height
$("#d1 *").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
$("#d1").height(biggestHeight);

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

Customized example for you http://jsfiddle.net/nWb5j/68/

Community
  • 1
  • 1
Kypros
  • 2,997
  • 5
  • 21
  • 27
0

Just use Math.max here is the demo

var  d2Height = $("#d2").height(),
     d3Height = $("#d3").height(),
     largest = Math.max(d2Height, d3Height);
  $('#d1').css({"height":largest});
Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78
0

In your case these two lines of javascript resolves the problem:

var height = Math.max($( "#d2" ).height(),$( "#d3" ).height());
$('#d1').height(height);

See updated fiddle:

http://jsfiddle.net/nWb5j/69/

zenichi
  • 124
  • 1
  • 3
0

You can try this...

var maxHeight =0;

//get the max height of child div
$(".d1 > div").height(function(i, h){
    if (h > maxHeight ) {
        maxHeight = h;
    }
});

$(".d1").height(maxHeight);