Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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.

An element's bounding boxes

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

like image 251
rvighne Avatar asked Jan 25 '14 17:01

rvighne


People also ask

How do you find the height of an element without padding?

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.

How do you find the height of an element with padding?

Using jQuery, you can get element height including padding with $(ele). outerHeight() , get element height including padding, border and margin by $(ele). outerHeight(true) .

Which method returns the width of an element with padding and border?

The outerWidth() method returns the width of an element (includes padding and border).

How do I find the size of an element in HTML?

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.


2 Answers

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;
}
like image 191
thetallweeks Avatar answered Oct 17 '22 16:10

thetallweeks


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);
like image 39
rvighne Avatar answered Oct 17 '22 15:10

rvighne