How do I retrieve an HTML element's actual width and height?
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:
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).
Handling CSS transformations
The getBoundingClientRect()
comes handy when your HTML element has undergone a CSS transformation.
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.
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.
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.
Was this article helpful?