How to get the height of a DIV considering inner element's margins?

前端 未结 11 3309
日久生厌
日久生厌 2021-02-20 04:20

Consider de following markup:

相关标签:
11条回答
  • 2021-02-20 04:44

    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, '') );
    
    0 讨论(0)
  • 2021-02-20 04:45

    I'd use jQuery. Try using

    $("#myelementId").height()
    

    And see if that does it.

    0 讨论(0)
  • 2021-02-20 04:45

    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.

    0 讨论(0)
  • 2021-02-20 04:49

    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).

    0 讨论(0)
  • 2021-02-20 04:52

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

    0 讨论(0)
提交回复
热议问题