Using getBoundingClientRect to Get an Element's Size and Position

William Le

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:

document.getElementById('foo').getBoundingClientRect();
// =>  {
//       top: Number,
//       left: Number,
//       right: Number,
//       bottom: Number,
//       x: Number,
//       y: Number,
//       width: Number,
//       height: Number,
//     } 
Learn JavaScript basics for free

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
}

Notes

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)

Specification

Read the official W3C specs for detailed information about getBoundingClientRect.

NameSpecificationStatus
getBoundingClientRectCSS Object Model (CSSOM) View ModuleWorking Draft
  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#