How to usegetComputedStyle() in Javascript

The getComputedStyle() method is used to get all the computed CSS property and values of the specified element. The use of computed style is displaying the element after stylings from multiple sources have been applied. The getComputedStyle() method returns a CSSStyleDeclaration object. 

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

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 (getComputedStyle)</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
        }
 
        #myDiv {
            width: 200px;
            height: 100px;
            background-color: #007BFF;
            margin-bottom: 10px;
        }
 
        #checkButtonComputed {
            margin: 10px;
            padding: 5px 10px;
            cursor: pointer;
        }
    </style>
</head>
 
<body>
 
    <div id="myDiv"></div>
    <button id="checkButtonComputed">
          Check Width (getComputedStyle)
      </button>
 
    <script>
        const myDiv = document.getElementById("myDiv");
        const checkButtonComputed =
              document.getElementById("checkButtonComputed");
 
        checkButtonComputed.addEventListener("click", () => {
            const computedStyle = window.getComputedStyle(myDiv);
            const width = computedStyle.getPropertyValue("width");
            alert("Width using getComputedStyle: " + width);
        });
    </script>
 
</body>
 
</html>


Output:

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()

...

Contact Us