Using the node.offsetWidth method can retrieve the width of an element, similar methods include:
- offsetHeight
- offsetTop
- offsetBottm
- offsetLeft
- offsetRight
Issue Arising#
The values obtained through the offset method are rounded using rounding, however, in some cases during development, precise values are needed. In such cases, using the offset method may not be feasible.
Solution#
By using the getBoundingClientRect() method, precise values of the element can be obtained (accurate to 6 decimal places).
Usage#
For example, node.getBoundingClientRect().width can retrieve the width of the element, similar methods include:
- getBoundingClientRect().height
- getBoundingClientRect().top
- getBoundingClientRect().bottom
- getBoundingClientRect().left
- getBoundingClientRect().right
Explanation#
getBoundingClientRect() returns a collection of rectangles. It represents the position of the current element in the browser and the space it occupies. Apart from width and height, other properties are calculated relative to the top left corner of the viewport, as shown in the image: