Reputation: 1850
I am using an Android WebView to display my app's HTML content. I need to dynamically find the full height of an element (usually a div) including padding, margin, and border. I am using JavaScript, and cannot use jQuery.
I have been using scrollHeight
on my div to get the height. I got the computed style of the div using var style = window.getComputedStyle(DIV, null);
and got the top and bottom margin by calling style.marginTop
and style.marginBottom
. They were both 0px. The problem is that scrollHeight
still does not account for the height of the margins belonging to div's.
I got the child elements of my div (usually a P or H* tag) and obtained the same fields the same way: scrollHeight
, marginTop
, and marginBottom
. The scrollHeight
s are the exact same (as I usually only have one child per div), but there is usually a top or bottom margin value in the child that is not reflected in the parent element.
I don't really understand why this is so. It appears as through the child's margin is rendered outside of parent, but the parent has no knowledge of it, and cannot directly access it.
I am looking for a way to access the margin defined by the child through the parent element. Is that possible?
This Question was very helpful, but I did not find an underlying reason for why it is rendered this way and the thread seems to have grown cold.
Thanks!
Upvotes: 2
Views: 251
Reputation: 1850
Sime Vidas pointed me in the right direction, so thanks!
I found myself trying to find out the exact height of the collapsed margins between divs and their children (but worded it much differently in my question). When accessing that information trough the DOM it will tell me style attributes of the parents and children, but it does not report the height of any collapsed margins.
So...the real answer to my question is NO. I have not been able to find a way to directly access the attribute of the collapsed margins.
What is just as good is taking the offsetTop
attribute of my div, and finding the difference between the offsetTop
attribute of the next Div. That gives the total height including final rendering of margins. To find the margins only, subtract the scrollHeight
.
This may not work in all scenarios, but was more than enough for my purposes.
Upvotes: 1