I'm looking for a robust way of determining the top margin of any DOM node that is rendered in the browser. This should work in all browsers. How can I do this? (Sometimes an element may have a specified margin in a stylesheet, but it may not actually be rendered by the browser if, for example, it has display:inline;
(see Margin top in inline element). I'm looking for the actual rendered margin. Therefore, using getComputedStyle()
won't work)
Asked
Active
Viewed 631 times
3

Community
- 1
- 1

user730569
- 3,940
- 9
- 42
- 68
-
actual redenered margin, so if the element has display inline, did you want js to return margin 0 or the margin that is set on the element in the css? sorry I am just confused, need a little clarification – Huangism Jul 05 '12 at 20:04
-
1He wants it to return 0. – Robin Jul 05 '12 at 20:08
2 Answers
1
Ok so does the following approach work?
Check if element is display inline, if so the margin top is 0
if not then get top margin

Huangism
- 16,278
- 7
- 48
- 74
-
-
My only question is, are there any other styles you would need to check for? – user730569 Jul 05 '12 at 20:34
-
0
There MIGHT be a way to do this with JQuery. If it's not what you want, I think you got what I'm after, maybe it can help you find something.
function getRenderedTopMargin(id){
var prevElementWidth;
var elementOffset = $('#'+id).offset();
var prevElementOffset = $('#'+id).prev().offset();
if ($('#'+id).css("display") == 'inline' || $('#'+id).prev().css("display") == 'inline'){
prevElementWidth = 0;
}else{
prevElementWidth = $('#'+id).prev().width();
}
return elementOffset.top - prevElementOffset.top - prevElementWidth;
}

Adi
- 5,089
- 6
- 33
- 47