Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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.

like image 460
Joe Avatar asked Aug 08 '14 06:08

Joe


People also ask

How do you find the inner height of an element?

The innerHeight() method returns the inner height of the FIRST matched element. As the image below illustrates, this method includes padding, but not border and margin. Related methods: width() - Sets or returns the width of an element.

Does element height include padding?

Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered). It does not include the height of pseudo-elements such as ::before or ::after .

Does width 100% include padding?

If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.

What is padding margin border?

In CSS, a margin is the space around an element's border, while padding is the space between an element's border and the element's content. Put another way, the margin property controls the space outside an element, and the padding property controls the space inside an element. Let's explore margins first.


1 Answers

Here's the solution that works for both cases of box-sizing: content-box and border-box.

var computedStyle = getComputedStyle(element);  elementHeight = element.clientHeight;  // height with padding elementWidth = element.clientWidth;   // width with padding  elementHeight -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom); elementWidth -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight); 

Works in IE9+

You can use feature detection

if (!getComputedStyle) { alert('Not supported'); }  

This will not work if element's display is inline. Use inline-block or use getBoundingClientRect.

like image 57
Dan Avatar answered Oct 23 '22 11:10

Dan