Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element width/height with margin, padding, border in Native JavaScript (no jQuery)

Tags:

javascript

dom

Looking for reliable method to calculate the element's width/height + margin - padding + border using native JS only and be xbrowser (IE8+)

TA

like image 360
Donatas Cereska Avatar asked Apr 24 '14 12:04

Donatas Cereska


People also ask

How do you find the height of an element with padding?

Using jQuery, you can get element height including padding with $(ele). outerHeight() , get element height including padding, border and margin by $(ele). outerHeight(true) .

How do I retrieve an HTML element's actual width and height?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

How do you find the height of an element without padding?

To get the height of an element minus padding, margin, border widths with JavaScript, we get the offsetWidth and offsetHeight and subtract them by the padding and border width and height. const cs = getComputedStyle(element); const paddingX = parseFloat(cs. paddingLeft) + parseFloat(cs.

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 .


1 Answers

If you're only dealing with pixel values for the margin, padding and border properties, you can do the following:

// we're assuming a reference to your element in a variable called 'element' var style = element.currentStyle || window.getComputedStyle(element),     width = element.offsetWidth, // or use style.width     margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight),     padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight),     border = parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);  alert(width + margin - padding + border); 

If you're dealing with other kinds of values (like ems, points or values like auto), I would like to refer you to this answer.

like image 187
reaxis Avatar answered Sep 26 '22 08:09

reaxis