The following picture displays the CSS box model that includes a block element with content, padding, border, and margin:
To get the element’s width and height that include the padding and border, you use the offsetWidth and offsetHeight properties of the element:
let box =document.querySelector('.box');let width =box.offsetWidth;let height =box.offsetHeight;Code language:JavaScript (javascript)
The following picture illustrates the offsetWidth and offsetHeight of an element:
See the following example:
<!DOCTYPE html><htmllang="en"><head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Getting the Width and Height of an Element</title></head><body> <divclass="box"style="width:100px;height:150px;border:solid 1px #000;padding:10px"></div> <script> let box = document.querySelector('.box'); let width = box.offsetWidth; let height = box.offsetHeight; console.log({ width, height }); </script></body></html>Code language: HTML, XML (xml)
Output:
{width:122, height: 172}Code language: CSS (css)
In this example:
The width is 100px
The border is 1px on each side, so 2px for both
The padding 10px on each side, so 20px for both
Therefore, the total width 12px. Similarly, the height is 172px.
To get the width & height of an element as floating-point after CSS transformation, you use the getBoundingClientRect() method of the DOM element. For example:
<!DOCTYPE html><htmllang="en"><head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Getting the Width and Height of an Element</title></head><body> <divclass="box"style="width:100px;height:150px;border:solid 1px #000;padding:10px"></div> <script> let box = document.querySelector('.box'); let width = box.offsetWidth; let height = box.offsetHeight; console.log({ width, height }); const domRect = box.getBoundingClientRect(); console.log(domRect); </script></body></html>Code language: HTML, XML (xml)