Joe Joe - 6 months ago 27
Javascript Question

Get the height of an element minus padding, margin, border widths

Does anyone know if it's possible to get just the height of an element (minus vertical padding, border, and margin) when there is no inline height declaration? I need to support IE8 and above.

el.style.height
doesn't work because the styles are set in an external style sheet.

el.offsetHeight
or
el.clientHeight
doesn't work because they include more than just the element's height. And I can't just subtract the element's padding, etc. because those values are also set in a CSS stylesheet, and not inline (and so
el.style.paddingTop
doesn't work).

Also can't do
window.getComputedStyle(el)
because IE8 doesn't support this.

jQuery has the height() method, which offers this, but I'm not using jQuery in this project, plus I just want to know how to do this in pure JavaScript.

Anyone have any thoughts? Much appreciated.

Answer

Here you go:

var style = window.getComputedStyle(document.getElementById("Example"), null);
style.getPropertyValue("height");

The above version will work in modern browsers. Please check currentStyle for IE browsers.

Cross browser:

try {
 el = window.getComputedStyle(document.getElementById('example'), null)
     .getPropertyValue('height');
} catch(e) {
 el = document.getElementById('example').currentStyle.height;
} 

source

Comments