Using getBoundingClientRect to Get an Element's Size and Position


While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

getBoundingClientRect, part of the JavaScript DOM (Document Object Model), provides you with important pieces of data about an HTML element’s size and positioning.

Using getBoundingClientRect

First, some simple markup:

<div id="foo">Hello World</div>

And now let’s call getBoundingClientRect on our #foo element:

// =>  {
//       top: Number,
//       left: Number,
//       right: Number,
//       bottom: Number,
//       x: Number,
//       y: Number,
//       width: Number,
//       height: Number,
//     } 

getBoundingClientRect returns an object with several fields and gives you sufficient information to infer everything about an HTML Element’s size and positioning within a webpage.

Here’s an illustration describing what each of the fields mean:

Illustrative example 1

There’s A LOT to chew on in this illustration. Take some time to let the info absorb!

Since the x and y values are redundant with left and top (respectively) and some browsers actually omit supplying them… You can sorta pretend like they don’t exist 🤭. It’s generally advisable to avoid using them for these reasons.

Another thing to notice is that right/bottom aren’t quite what you may be accustomed to in CSS positioning (eg.: when positioning using position: absolute).

Learning Exercise

Let’s try applying our knowledge! Given the illustration below what would be the output of getBoundingClientRect()?

Illustrative example 2

  top: 450,
  left: 400,
  right: 825,
  bottom: 500,
  x: 400,  // "x" is always equal to "left"
  y: 450,  // "y" is always equal to "top"
  width: 425,
  height: 50


getBoundingClientRect provides a rich amount of data, however the downside is that it can be overwhelming if you haven’t used it before.

Here’s some tidbits to remember that’ll help you!

  • The bottom and right values in getBoundingClientRect are different than how it’s used in CSS positioning.
  • Some browsers won’t include x and y values so it’s advisable to avoid using on them.
  • Since getBoundingClientRect is relative to the viewport, you can add window.scrollY and window.scrollX values to the top and left fields (respectively) to get the HTML element’s position relative to the entire webpage.

Browser Compatibility

getBoundingClientRect is reliably supported on all desktop and mobile browsers (with the exclusion of the x and y values which is unstable in IE/Edge and Safari)


Read the official W3C CSS Object Model (CSSOM) View Module spec for detailed information about getBoundingClientRect.


Creative Commons License