Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why `getBoundingClientRect()` and `getComputedStyle()` give different values

Why ball.getBoundingClientRect().bottom and parseInt(getComputedStyle(ball).bottom) give out different values here?

console.log( ball.getBoundingClientRect().bottom );
console.log( parseInt(getComputedStyle(ball).bottom) );
.ball {
  height           : 5rem;
  width            : 5rem;
  background-color : salmon;
  border-radius    : 50%;
  position         : relative;
  top              : 40vh;
  left             : 45vw;
}
<div class="ball"></div>

I was expecting the values to be same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The getBoundingClientRect().bottom gets the distance in pixels from the top of the viewport (window) and the bottom of the element. So if a box is 40px and it’s 10px away form the top of the window, the getBoundingClientRect().bottom returns 50

getBoundingClientRect docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

The getComputedStyle(element) get the rendered css (final result with all styles applied) from the element, so if you define bottom position to 10px, it’s gonna return 10.

getComputedStyle docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading