Getting the Width and Height of an Element

The following picture displays the CSS box model that includes a block element with content, padding, border, and margin:

CSS Box Model

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:

JavaScript offsetWidth and offsetHeight

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:

JavaScript clientWidth and clientHeight png

To get the margin of an element, you use the getComputedStyle() method:

To get the border width of an element, you use the property of the style object returned by the getComputedStyle() method:

To get the height and width of the window, you use the following code:

Summary

  • Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

Last updated