Reputation: 5829
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:
#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
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
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
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