最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the height of a DIV considering inner element's margins? - Stack Overflow

programmeradmin3浏览0评论

Consider de following markup:

<div id="outerElement">
    <div id="innerElement" style="border: 1px solid blue; background-color: #f0f3f5; margin-top: 100px">  
        TESTE
    </div>
</div>

I want to get the actual final height of outerElement using javascript. I noticed that if I remove the vertical margins from innerElement I am able to get what I want but I cannot alter styles from within the outerElement.

How do I do this?

Obs: I already tried height, scrollheight and offsetHeight in all browsers. Chrome gives me the expected value (including inner element's margins) for scrollHeight. All other browsers fail.

Consider de following markup:

<div id="outerElement">
    <div id="innerElement" style="border: 1px solid blue; background-color: #f0f3f5; margin-top: 100px">  
        TESTE
    </div>
</div>

I want to get the actual final height of outerElement using javascript. I noticed that if I remove the vertical margins from innerElement I am able to get what I want but I cannot alter styles from within the outerElement.

How do I do this?

Obs: I already tried height, scrollheight and offsetHeight in all browsers. Chrome gives me the expected value (including inner element's margins) for scrollHeight. All other browsers fail.

Share Improve this question asked Mar 31, 2010 at 17:13 Andre PenaAndre Pena 59.3k53 gold badges208 silver badges257 bronze badges 1
  • None of the answers down (as of december 2011) makes sense, I wonder if you found a workaround? – Jan Commented Dec 1, 2011 at 19:21
Add a comment  | 

11 Answers 11

Reset to default 2

If you can set the outer div to style display : inline-block; then scrollHeight will include the margins of child elements.

It will also work if you set style display : flex; (supported by IE 9+)

I'd use jQuery. Try using

$("#myelementId").height()

And see if that does it.

Add clearfix, use jquery height() and remove the clearfix class again.

That's gonna work. : )

you could use jQuery:

$('#outerElement').height(); // gets the height of the div
$('#outerElement').outerHeight(); // gets the height of the div including margins and padding
$('#outerElement').innerHeight(); // gets the height of the div including padding

one of those is bound to work.

Try using clientHeight

var outerElement = document.getElementById("outerElement");
if(outerElement.clientHeight) {
alert("Height is "+outerElement.clientHeight+"px");
}
else { alert("Old browser?"); }

I know what you're thinking... "this won't work!" and alas, it doesn't... but if you do something like add a border to outerElement... even for just a moment...

var outerElement = document.getElementById("outerElement");
outerElement.style.border = "1px solid black";
var height = outerElement.clientHeight;
outerElement.style.border = "none";
alert("Height is "+height+"px");

Not the most beautiful solution but it works, and if you can figure out why it works (I sure as hell don't know :P) you might be closer to a good solution...

Some older browsers may not support it though... you'd have to look into it; I can't list 'em.

ok also not pretty but this is how I do it (disclaimer: I stole this from somewhere once)

var height = elem.clientHeight + getBufferHeight(elem, true);

function getBufferHeight(elem, includeMargins) {
    if (!elem.visible()) {
        return 0;
    }
    //do new Number instead of parseFloat to avoid rounding errors 
    var result = 0;
    if (includeMargins) {
        result =   
            new Number(elem.getStyle('marginTop').replace(/[^\d\.]/g, '')).ceil() +  
            new Number(elem.getStyle('marginBottom').replace(/[^\d\.]/g, '')).ceil();
    }     
    result +=
        new Number(elem.getStyle('borderBottomWidth').replace(/[^\d\.]/g, '')).ceil() +
        new Number(elem.getStyle('borderTopWidth').replace(/[^\d\.]/g, '')).ceil() +    
        new Number(elem.getStyle('paddingTop').replace(/[^\d\.]/g, '')).ceil() +
        new Number(elem.getStyle('paddingBottom').replace(/[^\d\.]/g, '')).ceil();                        
    return result;
}

This is a tricky question as what do you discern as the "appropriate" height. The height of the content inside including borders, what about padding, or the actual margin use? In general browser act fairly consistent on most things, but quirksmode can clear up what you need. (As a hint, if you need the actual margin used, its gonna hurt).

I guess you should go throw all element properties and the make a sum only in this way you can know the exactly height... but in the case of the height is set it by for example clear:both property I dont think is posible to know the heigth of an Element.

A 3 sec thought could be something like:

var o document.getElementById('id').style;

    var total = ((o.height.split("px")[0] == "") ? 0 : o.height.split("px")[0]) +
 ((o.marginTop.split("px")[0] == "") ? 0 : o.marginTop.split("px")[0]) + 
((o.marginBottom.split("px")[0] == "") ? 0 : o.marginBottom.split("px")[0]) + 
((o.paddingTop.split("px")[0] == "") ? 0 : o.paddingTop.split("px")[0]) +
    ((o.borderTop.split("px")[0] == "") ? 0 : o.borderTop.split("px")[0]) +
 ((o.borderBottom.split("px")[0] == "") ? 0 : o.borderBottom.split("px")[0])

But I guess you must include also the document.getElementById('id').height value if have it.... is thougth but can help..

best =)

WARNING WARNING clientHeight almost works but doesn't include margins :(

Just thought I'd add that I've been trying this today, and while nahumsilva & plodder almost have it right (nahumsilva's version appears to be more cross-browser {plodder's doesn't appear to work in Chrome/WebKit, but I'm no expert on these things}), they've both missed that an element may have computed style elements that aren't defined by it's own style.

This was driving me nuts - I was wondering where my <p> elements were getting an extra 16px of margin height - until I realised it was coming from the computed style.

So, long story short, an approach like nahumsilva / plodder worked for me, with the added proviso that you should get the element's computed style with window.getComputedStyle( element, null ), which returns a CSSStyleDeclaration object (like element.style). element.offsetHeight / element.clientHeight should give you the height without margins, so the whole thing looks like:

var cstyle = window.getComputedStyle( element, null );
var elementHeight = element.offsetHeight +
Number( cstyle.marginBottom.replace(/[^\d\.]/g, '') ) +
Number( cstyle.marginTop.replace(/[^\d\.]/g, '') );

try $("#myelementId").outerHeight( true )

This answer may be a little obvious, but if you already know the margin, why not just manually add it to the height?

发布评论

评论列表(0)

  1. 暂无评论