Calculate the total height of child elements of a clipped (overflow: hidden) parent tag

Ever have an element with clipped content and wanted to know the total height of the elements contained therein? I have a client who wants the height of the main content to be clipped to a preset height (don’t ask me why). Which means I need to dynamically add a “read more” link to expand the container and show all the content.

Well, here’s how you calculate the combined height of the children with jQuery…

HTML

<div id="container" style="height: 1em; overflow: hidden">
    <p>content<br />content<br />content<br />
    content<br />content<br />content<br />
    content<br />content<br />content</p>
    <p>content<br />content<br />content<br />
    content<br />content<br />content<br />
    content<br />content<br />content</p>
</div>

JavaScript

var totalHeight = 0;
$("#container").children().each(function(){
    totalHeight += $(this).outerHeight(true); // true = include margins
});
alert("Total Height: " + totalHeight + "px");

Result

Total Height: 360px

All you have to do is loop over each child element inside the parent element, adding its outerHeight (which includes margins, borders and padding) to the totalHeight variable.

3 thoughts on “Calculate the total height of child elements of a clipped (overflow: hidden) parent tag”

  1. Old thread, but I was looking this up so I would suggest this:


    var totalHeight = $('#container').prop('scrollHeight');

Leave a Reply

Your email address will not be published. Required fields are marked *