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:
Output:
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:
Output:
clientWidth & clientHeight
To get the element’s width and height that include padding but without the border, you use the clientWidth and clientHeight properties:
The following picture illustrates the clientWidth and clientHeight of an element:
let box = document.querySelector('.box');
let width = box.clientWidth;
let height = box.clientHeight;Code language: JavaScript (javascript)
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let marginLeft = parseInt(style.marginLeft);
let marginRight = parseInt(style.marginRight);
let marginTop = parseInt(style.marginTop);
let marginBottom = parseInt(style.marginBottom);Code language: JavaScript (javascript)
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let borderTopWidth = parseInt(style.borderTopWidth) || 0;
let borderLeftWidth = parseInt(style.borderLeftWidth) || 0;
let borderBottomWidth = parseInt(style.borderBottomWidth) || 0;
let borderRightWidth = parseInt(style.borderRightWidth) || 0;
Code language: JavaScript (javascript)
let width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;Code language: JavaScript (javascript)