Using the node.offsetWidth
method can get the width of the element, similar methods are as follows:
- offsetHeight
- offsetTop
- offsetBottm
- offsetLeft
- offsetRight
Problem Arising#
The values obtained through the offset method are rounded in a round-up manner. However, in some cases during our 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 get the width of the element, similar methods are as follows:
- getBoundingClientRect().height
- getBoundingClientRect().top
- getBoundingClientRect().bottom
- getBoundingClientRect().left
- getBoundingClientRect().right
Detailed 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: