2

I'm looking for a solid, cross-browser way of finding the following calculated dimensions from Javascript:

  • content rectangle: innermost content area
  • client rectangle: content area + padding
  • complete rectangle: content + padding + border + margin

It doesn't have to be exactly that grouping, I'm just looking for enough info to completely decompose any box into content->padding->border->margin segments.

(I probably won't have to care about scroll bars, but if they have a well-defined behaviour as well, I wouldn't mind knowing that)

I want to be able to get these as pixel values, regardless of how they were styled from CSS. So even in the case of e.g. margin-left: auto or width: 50%, I want to be able to extract the computed results in pixels.

No jQuery solutions please, I'm looking for vanilla Javascript + DOM answers.

tbone
  • 166
  • 1
  • 10

2 Answers2

0

The jQuery way of doing it would be to call .outerWidth() or .outerHeight(). In not being able to use jQuery, you could take a look into the jQuery source to see how they achieve this.

Alternatively, there are a few answers here which yield the same results. E.g.: what is the jQuery outerHeight() equivalent in YUI & outerWidth without jquery.

From the latter:

document.getElementById('container').offsetWidth; // "Outer" Width
document.getElementById('container').clientWidth; // "Inner" Width

With .offsetHeight and .clientHeight for heights, respectively.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Use `$('#elementId').innerHeight()` and `$('#elementId').innerWidth()` for the content width. – Rembunator Feb 14 '13 at 14:14
  • 1
    Actually, both innerWidth() and outerWidth() includes padding, with outerWidth() also including border and optionally margin. Frankly, I was hoping I wouldn't have to sift through the entire jQuery source to find these answers; surely someone else must have done this without jQuery? – tbone Feb 14 '13 at 14:17
0

This may help:

<style>
  body { 
    margin: 10%;
    padding:10px 0 0;
    border:1px solid #000;
  }
</style>

var elem = document.body;

var computedStyle = window.getComputedStyle ? getComputedStyle(elem, '') : elem.currentStyle;

var marginTop = computedStyle.marginTop;
var borderTop = computedStyle.borderTopWidth;
var paddingTop = computedStyle.paddingTop;
console.log(marginTop);
console.log(borderTop);
console.log(paddingTop);

// for me returns 168px, 1px, 10px

But it returns percents for IE < 9. For older versions you should transform percents to pixels (you can find more here http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291)

JohnV
  • 41
  • 2
  • Looks like you're on to something here... I'll give this a go when I revisit the problem. – tbone Aug 25 '13 at 22:20