In this post we are going to discuss how to get the height and width of an element with Javascript.

There are several properties we can look at in order to get the width and height of elements, and it can be tricky to determine which is the right one for your needs. Let’s discuss about some of these.

const containerEle = document.getElementById("container");

const clientWidth = containerEle.clientWidth;
const clientHeight = containerEle.clientHeight;

const offsetWidth = containerEle.offsetWidth;
const offsetHeight = containerEle.offsetHeight;

const scrollWidth = containerEle.scrollWidth;
const scrollHeight = containerEle.scrollHeight;

console.log({
	clientWidth,
	clientHeight,
	offsetWidth,
	offsetHeight,
	scrollWidth,
	scrollHeight
});

offsetWidth

The offsetWidth read-only property returns the layout width of an element in pixels as an integer.

offsetWidth = borders + padding + content + and vertical scrollbars (if rendered)

It does not include the width of pseudo-elements such as ::before or ::after.

offsetHeight

The offsetHeight read-only property returns the height of an element in pixels, including vertical padding and borders, as an integer.

offsetHeight = borders + padding + content + and horizontal scrollbars (if rendered)

It does not include the width of pseudo-elements such as ::before or ::after.

clientWidth

The clientWidth property is zero for inline elements and elements with no CSS; otherwise, it’s the inner width of an element in pixels.

clientWidth = padding + content - borders - margins - and vertical scrollbars (if present)

clientHeight

The clientHeight read-only property is zero for elements with no CSS or inline layout boxes; otherwise, it’s the inner height of an element in pixels.

clientWidth = padding + content - borders - margins - and horizontal scrollbars (if present)

scrollWidth

The scrollWidth property returns the width of an element in pixels, including padding, excluding borders, scrollbars or margins.

scrollWidth = padding + content - borders - margins - and vertical scrollbars (if present)

scrollHeight

The scrollHeight property returns the height of an element in pixels, including padding, but excluding borders, scrollbars, or margins.

scrollHeight = padding + content - borders - margins - and horizontal scrollbars (if present)

Both scrollWidth and scrollHeight return the entire height and width of an element, including what is not viewable because of overflow.

All these properties are read-only.

Example

I hope at this point it must be clear to determine which is the right one for your needs.

If you find it helpfull please share with your network ✅.

Happy Coding 🙌 !