Get Width And Height Of HTML Element Using JavaScript

JavaScript

19/07/2021


There are a few ways you can retrieve the width and height of an HTML element on your page. However, it's important to know what these measurements are made up of: the content, padding, border and margin.

Parts of an HTML element

Box model in HTML

In all the following methods, the margin is always excluded from and the content is always included in the height and width calculations.

Method 1

The offsetHeight and offsetWidth read-only properties return a value that includes the border, padding and scroll bar. If the element is hidden, then both properties will return 0.

JAVASCRIPT
const htmlElement = document.getElementById('some-id')
htmlElement.offsetHeight
htmlElement.offsetWidth

Offset property

Sourced from MDN Web Docs

Method 2

Similarly, clientHeight and clientWidth are read-only properties. However, the returned value solely includes the padding. Take notice that for inline elements, these properties return 0.

JAVASCRIPT
htmlElement.clientHeight
htmlElement.clientWidth

Client property

Sourced from MDN Web Docs

Method 3

Another way to measure an element's dimensions is using getBoundingClientRect(). It's main advantage over the other 2 methods is that it gives you fractional values instead of rounding them to the nearest integer.

JAVASCRIPT
const elementDimensions = htmlElement.getBoundingClientRect()
elementDimensions.height
elementDimensions.width

It returns an object of type DOMRect that contains the height and width of the element. And like offset..., the border, padding and scroll bar are included in the measurements.


WRITTEN BY

Code and stuff