Why is my clientWidth and offsetWidth equal?

2.1k Views Asked by At

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}
<div id="mydiv">
  <div id="div1"></div>
</div>

I have a div on a webpage where the content requires a vertical scrollbar. Using javascript, I'm trying to calculate the offsetWidth and clientWidth so that I can ultimately calculate the width of the vertical scrollbar but apparently they are equal. I have:

html:

<div id="mydiv">
  <div id="div1"></div>
</div>

css:

#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}

js:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
2

There are 2 best solutions below

0
Himanshu Joshi On

Main difference between clientWidth and offsetWidth :

(1) clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars)

(2) offsetWidth is the outer width (ie. the space occupied by the element, including padding and borders)

As I can see in your CSS border and scrollbars is missing that is why you are getting same width in both case.

I have made updated CSS and now you will get different values. Please check below snippet:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
#mydiv {
        padding: 20px;
        border: 20px solid red;
      }
<div id="mydiv">
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
  </div>

4
Akhil Aravind On

Take a look at the two snippet, you can see the difference with scrollbar and without scrollbar.

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
#div1 {
  height: 100px;
  width: 200px;
  background-color: #000000;
}
#mydiv{
  height:80px;
  width:160px;
  overflow:scroll
}
<div id="mydiv">
  <div id="div1"></div>
</div>

Below snippet has no scrollbar and overflow, so the client width and offset width are same

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
#div1 {
  height: 100px;
  width: 200px;
  background-color: purple;
}
<div id="mydiv">
  <div id="div1"></div>
</div>