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).
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.
Using jQuery, you can get element height including padding with $(ele). outerHeight() , get element height including padding, border and margin by $(ele). outerHeight(true) .
The outerWidth() method returns the width of an element (includes padding and border).
If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the HTMLElement. offsetWidth and HTMLElement. offsetHeight properties. Most of the time these are the same as width and height of Element.
element.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With