Does getBoundingClientRect().width and height properties, while returning values include paddings and borders of element?
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.
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.
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>
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