Reputation: 15293
I am calulating the childrens
height, to add the scrollbar to the container. but it's not come as perfect. any one help me to calculate the childrens height perfectly?
here is my js :
var p= "</p>Some testing text</p>";
var getAllHeight = function (content) {
var allHeight = 0;
$('#container').children().not('.content').each(function(){
allHeight += $(this).outerHeight(true);
});
return allHeight;
}
var addHeight = function () {
var content = $('.content');
var allHeight = getAllHeight(content);
var rest = $('#container').innerHeight() - allHeight;
if(content.outerHeight() > rest) {
content.css('height', (content.outerHeight() - allHeight ));
}
console.log(allHeight, content.height(), content.outerHeight(),content.innerHeight())
};
$('button').click(function(){
$('.content').append(p);
addHeight();
});
<div id="container">
<div>
<h2>Heading</h2>
</div>
<div>
<h2>Heading</h2>
</div>
<div class="content">
</div>
<div class="footer">
Footer
</div>
<div class="button"><button>Add</button></div>
</div>
Upvotes: 1
Views: 39
Reputation: 193261
This is CSS issue due to collapsing margins (read "Parent and first/last child" case) on div>h2
structure. Since div
containers don't have any padding, margin or border, their margins collapse to accommodate inner margin. Simple fix is to set some padding on them or border or set h2
to inline-block.
Another issue is that when there is not enough space you should set content
height to rest
.
if (content.outerHeight() > rest) {
content.css('height', rest);
}
Demo: http://jsfiddle.net/doesfmnm/5/
Upvotes: 1