tuscan88
tuscan88

Reputation: 5829

get computed height of div with jquery

If I have a div that is positioned relative and then some divs inside that which are positioned absolute the parent div will have no height. The contents of the div can change though so I need a way to calculate the height of the contents and set the height of the parent dynamically. Is there a simple way to do this in jquery? See the following example:

http://jsfiddle.net/vgyrbcbs/

#parent {
    position: relative;
}
.child {
    position: absolute;
    width: 100px;
    height: 100px;
    background: #ff0000;
}  
#child1 {
    top:0;
    left:0
}
#child2 {
    top:50px;
    left:150px;
}
#child3 {
    top:150px;
    left:20px;
}
#child4 {
    top:250px;
    left:150px;
}
<div id="parent">
    <div class="child" id="child1"></div>
    <div class="child" id="child2"></div>
    <div class="child" id="child3"></div>
    <div class="child" id="child4"></div>
</div>

How would I work out the height of the parent?

Upvotes: 0

Views: 705

Answers (4)

rasah_dipikir_jerojero
rasah_dipikir_jerojero

Reputation: 175

try to count the last div (child 4) offset top + child 4 height - parent offset top

try this

var parent_height = $('#child4').height()+$('#child4').offset().top-$('#parent').offset().top;

Upvotes: 0

Rhumaric
Rhumaric

Reputation: 56

The parent's height is actually 0 because all the elements are positionned absolutely. If you're looking for the height of the content, the scrollHeight property of the parent will give you that information.

$('#parent')[0].scrollHeight; // or
$('#parent').get(0).scrollHeight; // or
$('#parent').prop('scrollHeight'); 

Upvotes: 3

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2596

Something like this : http://jsfiddle.net/vgyrbcbs/2/

var height = 0;

$("#parent div").each(function () {
   height += parseInt($(this).css("height").split("px")[0]);

});

$("#parent").css("height", height);

UPDATE

You can check the last div if it's always at the bottom like this : http://jsfiddle.net/vgyrbcbs/4/

$("#parent").css("height", parseInt($("#parent div:last").css("top").split("px")[0]) + parseInt($("#parent div:last").css("height").split("px")[0]));

Upvotes: 3

vp_arth
vp_arth

Reputation: 14982

Try:

var h = 0;
$('#parent .child').each(function(){h = Math.max($(this).offset().top + $(this).height(), h);})
alert(h);

I just search height as top+height of bottom child element

Fiddle

Upvotes: 0

Related Questions