How to usegetBoundingClientRect() in Javascript

The HTML DOM getBoundingClientRect() Method returns the relative positioning to the viewport. It returns 8 properties: left, top, right, bottom, x, y, width, and height. Scrolling will change the position value. 

Example: In this example, we are using getBoundingClientReact().

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Check Width (getBoundingClientRect)</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
        }
 
        #myDiv {
            width: 200px;
            height: 100px;
            background-color: #007BFF;
            margin-bottom: 10px;
        }
 
        #checkButtonBounding {
            margin: 10px;
            padding: 5px 10px;
            cursor: pointer;
        }
    </style>
</head>
 
<body>
 
    <div id="myDiv"></div>
    <button id="checkButtonBounding">
        Check Width (getBoundingClientRect)
    </button>
 
    <script>
        const myDiv = document.getElementById("myDiv");
        const checkButtonBounding =
            document.getElementById("checkButtonBounding");
 
        checkButtonBounding.addEventListener("click", () => {
            const rect = myDiv.getBoundingClientRect();
            const width = rect.width;
            alert("Width using getBoundingClientRect: " + width);
        });
    </script>
 
</body>
 
</html>


Output:

Note: clientWidth returns the inner width which includes padding but excludes borders and scroll bars whereas offsetWidth returns the outer width which includes padding and borders.



How to find the width of a div using vanilla JavaScript?

To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels.

Below are the different approaches to finding the width of a div using vanilla JavaScript:

Table of Content

  • Using offsetWidth
  • Using clientWidth()
  • Using getComputedStyle()
  • Using getBoundingClientRect()

Similar Reads

Approach 1: Using offsetWidth

The DOM offsetWidth property is used to return the layout width of an element as an integer....

Approach 2: Using  clientWidth()

...

Approach 3: Using getComputedStyle()

The DOM clientWidth Property is used to return the viewable width of a specific element including padding but excluding the measurement of margin, border, and scrollbar width....

Approach 4: Using getBoundingClientRect()

...