最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the dimensions of a DOM element, minus border and padding? - Stack Overflow

programmeradmin0浏览0评论

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

Share Improve this question asked Jan 25, 2014 at 17:53 rvighnervighne 21.9k11 gold badges53 silver badges75 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

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);
发布评论

评论列表(0)

  1. 暂无评论