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

前端 未结 14 1852
后悔当初
后悔当初 2020-11-22 02:29

Suppose that I have a

that I wish to center in the browser\'s display (viewport). To do so, I need to calculate the width and height of the &l
14条回答
  •  眼角桃花
    2020-11-22 02:49

    You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

    var width = document.getElementById('foo').offsetWidth;

    Function .getBoundingClientRect() returns dimensions and location of element as floating-point numbers after performing CSS transforms.

    > console.log(document.getElementById('id').getBoundingClientRect())
    DOMRect {
        bottom: 177,
        height: 54.7,
        left: 278.5,​
        right: 909.5,
        top: 122.3,
        width: 631,
        x: 278.5,
        y: 122.3,
    }
    

提交回复
热议问题