简体   繁体   中英

How to get the dimensions of a DOM element, minus border and padding?

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).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM