How can I get the size of the content-box of a <div>
(or any other element) using pure JavaScript? By content-box, I don't mean the size of text inside the div, I mean the element's on-screen size minus border and padding.
This is what I see in Chrome Dev Tools. I want just the blue part (720 x 540) in JavaScript. My problem with offsetHeight
and company is that they return the dimensions of the black solid rectangle in the graphic (it's hard to see -- between margin and border).
Note that the width
and height
CSS properties may or may not be set; I want the dimensions regardless. Further note that padding and border may or may not be consistent (it might have only one border, for example).
How can I get the size of the content-box of a <div>
(or any other element) using pure JavaScript? By content-box, I don't mean the size of text inside the div, I mean the element's on-screen size minus border and padding.
This is what I see in Chrome Dev Tools. I want just the blue part (720 x 540) in JavaScript. My problem with offsetHeight
and company is that they return the dimensions of the black solid rectangle in the graphic (it's hard to see -- between margin and border).
Note that the width
and height
CSS properties may or may not be set; I want the dimensions regardless. Further note that padding and border may or may not be consistent (it might have only one border, for example).
2 Answers
Reset to default 11element.clientWidth
will give you the width including padding (but no border).
Then, you can parseFloat
the values of paddingLeft
and paddingRight
. Here is an example:
function getElementContentWidth(element) {
var styles = window.getComputedStyle(element);
var padding = parseFloat(styles.paddingLeft) +
parseFloat(styles.paddingRight);
return element.clientWidth - padding;
}
I found a solution that seems to work correctly and is fairly well-supported. But I will still accept other answers that do not require parsing numbers out of strings. There has to be another way!
var style = window.getComputedStyle(my_div);
var width = parseFloat(style.width);
var height = parseFloat(style.height);