I want to calculate the total "height" of a div element considering the effect of collapsed margins because of child elements, that is, the total space that div element occupies in the document. I'm having a hard time thinking of the best algorithm / approach to do this.
Consider, for example, a div element with a margin-top
of 10px
and a height
of 50px
. This div element has a child <h2>
element that has a margin-top
of 20px
. The div
's margin
will then collapse and the actual "height"
of that div
will be 70px
. However, using jQuery methods, we are only able to get the height
of the div
without considering it's margins
, or considering it's 10
pixel margin
which would give us the wrong value:
$(elem).outerHeight() // 50
$(elem).outerHeight(true) // 60
To help illustrate my point, here is a jsfiddle I created with two examples.
My best guess at the moment is we have to iterate over all children of the div in some way and calculate the highest top and bottom margin.
According to what I understand from the W3C specification, we can skip this iteration for the top margin
if the target div has a top-border-width
or a top-padding
. Ditto for the bottom margin
.
Any help would be greatly appreciated. Thanks!
EDIT:
One (ugly) solution I thought about was wrapping the target div element in another div. Then, we quickly add and remove a transparent borderTop and borderBottom to the wrapping div, measuring it's height in between. The borders will force the wrapping div's margin not to collapse with its children's margins. Something like this:
var collapsedHeight = function( target ) {
var $wrapper = $('<div />'),
$target = $(target);
$wrapper.insertAfter($target);
$target.appendTo($wrapper);
$wrapper.css({
borderTop: '1px solid transparent',
borderBottom: '1px solid transparent'
});
var result = $wrapper.outerHeight() - 2;
$target.insertAfter($wrapper);
$wrapper.remove();
return result;
};
I made a jsFiddle for it here.