Explain Codes LogoExplain Codes Logo

How do I retrieve an HTML element's actual width and height?

javascript
getboundingclientrect
offsetwidth
offsetheight
Nikita BarsukovbyNikita Barsukov·Dec 30, 2024
TLDR

You can get an element's size with the getBoundingClientRect() function. It returns the width and height reflecting the element's dimensions. Here's a simple example:

const rect = document.querySelector('.element').getBoundingClientRect(); console.log(`Width: ${rect.width}, Height: ${rect.height}`);

Please replace .element with your actual selector. The values are in pixels, and include padding.

What are offsetWidth and offsetHeight?

Besides getBoundingClientRect(), there are offsetWidth and offsetHeight properties that you can use to get the dimensions. They give the total pixel dimensions of an element, including padding, borders, and scrollbar (if present).

let el = document.querySelector('.element'); let width = el.offsetWidth; // Unit: pixels (px) let height = el.offsetHeight; // Unit: pixels (px) // Like Dorothy in The Wizard of Oz, these values don't care about transformations

Handling CSS transformations

The getBoundingClientRect() comes handy when your HTML element has undergone a CSS transformation.

let rect = el.getBoundingClientRect(); // You can't hide from me, transformations! I see right through your tricks. console.log(`Width: ${rect.width}, Height: ${rect.height}`);

Remember, this doesn't account for margins. Keep that in mind for precise calculations.

jQuery to the rescue

jQuery provides nice and simple width() and height() methods that take care of browser differences. A big plus: they don't consider padding, borders, or scrollbars.

let $el = $('.element'); let width = $el.width(); // Unit: pixels (px) let height = $el.height(); // Unit: pixels (px)

Moreover, jQuery offers outerWidth() and outerHeight() when you wish to include padding and border in your measurement.

Tackling browser compatibility

There are old browsers (Ahem, IE8!) that don't support getBoundingClientRect(). For these, use clientWidth and clientHeight or jQuery for better cross-browser compatibility.

Including padding and borders

With CSS's box-sizing set to border-box, getBoundingClientRect().width and .height help you avoid the task of manually adding padding and borders.

Centering elements

For centering an element in the viewport, just do the maths with the calculated dimensions.

document.querySelector('.element').style.transform = `translate(${(window.innerWidth - width) / 2}px, ${(window.innerHeight - height) / 2}px)`; // Abra-cadabra! Your element is now dead center.

Manipulating element's rectangle

Although the getBoundingClientRect() returns a DOMRect object that is read-only, you can convert it into a regular object and manipulate the data as needed.

const rect = el.getBoundingClientRect(); const rectObj = { ...rect }; // Spread operator to copy rectangle data to a new object