Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does getBoundingClientRect().width and height includes paddings and borders of element?

Tags:

javascript

Does getBoundingClientRect().width and height properties, while returning values include paddings and borders of element?

like image 301
RoseCrime Avatar asked Jun 02 '18 13:06

RoseCrime


1 Answers

TLDR;

It will always return dimensions of the border box (green box bellow), which contains the content area, padding area and border area, as defined in the CSS Box Model.

CSS Box Model

The width style

However, one must not conflate content width (a property of the element layout) and style width (a constraint on the element layout, width: xxx; rules) which are very distinct things. The box-sizing will only affect whether the style width constraint should include the border and padding, or not.

Demonstration by example

In this first snippet, we are using box-sizing: border-box rule so that style width == boder + padding + content width. The result of getBoundingClientRect().width is 140, and it equals style width.

var x = document.getElementById("x");
console.log('getBoundingClientRect().width =', x.getBoundingClientRect().width);
console.log('getComputedStyle(x).width =', getComputedStyle(x).width);
#x {
  border: 20px solid blue;
  padding: 10px;
  width: 140px;
  box-sizing: border-box;
}
<div id=x>Border Box</div>

In the second snippet, we are using box-sizing: content-box rule so that style width == content width. The result of getBoundingClientRect().width is still 140 because the sum of border + padding + content width has not changed, only style width has changed.

var y = document.getElementById("y");
console.log('y.getBoundingClientRect().width =', y.getBoundingClientRect().width);
console.log('getComputedStyle(y).width =', getComputedStyle(y).width);
#y {
  border: 20px solid blue;
  padding: 10px;
  width: 80px;
  box-sizing: content-box;
}
<div id=y>Content Box</div>

References

  • MDN | Introduction to the CSS box model
  • CSSWG | CSS2 (Box Model)
  • MDN | Element.getBoundingClientRect()
like image 59
Jules Sam. Randolph Avatar answered Oct 18 '22 05:10

Jules Sam. Randolph