I want to calculate the total "height" of a div element, taking into account the effect of collapsing margins due to child elements, that is, the total space that the div element occupies in the document. I find it difficult to think of a better algorithm / approach for this.
Consider, for example, a div element with margin-top
of 10px
and a height
of 50px
. This div element has a child element <h2>
that has margin-top
of 20px
. Then the div
margin
will crash and the actual "height"
this div
will be 70px
. However, using jQuery methods, we can get the height
div
without considering its margins
or by counting it 10
pixel margin
, which would give us the wrong value:
$(elem).outerHeight()
To illustrate my point here is the jsfiddle I created with two examples.
My best guess at the moment is that we have to somehow sort through all the children of the div and calculate the height of the top and bottom margins. According to what I understand from the W3C spec, we can skip this iteration for the top margin
if the target div has top-border-width
or top-padding
. The same goes for the bottom margin
.
Any help would be greatly appreciated. Thanks!
EDIT:
One (ugly) solution I was thinking of was wrapping the target div element in another div. Then we quickly add and remove the transparent borderTop and borderBottom to the wrapper div, measuring its height between them. Borders will force the edge of the wrapping div to not fall off with its child fields. Something like that:
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 jsFiddle for it here .
source share