42

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

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Donatas Cereska
  • 515
  • 1
  • 5
  • 11

1 Answers1

65

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.

Community
  • 1
  • 1
reaxis
  • 1,361
  • 12
  • 11
  • 13
    +1 I liked it since you have covered all the points, although you could have mentioned `element.getBoundingClientRect` function, in your answer. – Mehran Hatami Apr 24 '14 at 13:37
  • 1
    Remember you have to declare the widths as `border-left-width` or `border-right-width` in css though. It will not parse left width from a style declared as `border-width` or simply `border`. – AbsoluteƵERØ May 16 '14 at 22:44
  • 2
    The ´element.offsetWidth´ already includes the sizes of the borders, but in your last codeline you sum up the borders again. You added the border width twice. Perhaps better use ´clientWidth´ instead ´offsetWidth´. – Simon Dec 28 '19 at 12:56