HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howwidthandheightretrieveelementhtmlactual

Problem

How can I calculate the width and height of a `` element, so as to be able to center it in the browser's display (viewport)? What browsers support each technique?

Solution

You should use the .offsetWidth and .offsetHeight properties.
Note they belong to the element, not .style.
var width = document.getElementById('foo').offsetWidth;


The .getBoundingClientRect() function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms.
> console.log(document.getElementById('foo').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,​
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}

Context

Stack Overflow Q#294250, score: 1745

Revisions (0)

No revisions yet.