Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

Element.getBoundingClientRect()

Reference for Element.getBoundingClientRect(): get an element's size and viewport position as a DOMRect, convert to page coordinates and avoid layout thrashing.

The getBoundingClientRect() method returns a DOMRect that describes the rectangle an element occupies on screen: its size, and its position relative to the top-left corner of the viewport. The rectangle covers the element's border box (content, padding and border) and includes the effect of CSS transforms.

Because the numbers are relative to the viewport, they change when the page scrolls. They are a snapshot taken at the moment of the call.

JavaScript
const rect = element.getBoundingClientRect();
console.log(rect.top, rect.left, rect.width, rect.height);

Try it

Size, transforms and position
Viewport versus page coordinates

Syntax

JavaScript
element.getBoundingClientRect()

Parameters: none.

Return value: a DOMRect with these read-only values, all in CSS pixels and possibly fractional:

Property Description
x, y The top-left corner relative to the viewport. For normal (non-negative) sizes they equal left and top.
width, height The size of the rectangle.
top, left Distances from the viewport's top and left edges.
bottom, right Distances from the viewport's top and left edges to the bottom and right edges of the rectangle.

The object also has a toJSON() method.

Usage notes

  • Viewport-relative. To get a position within the whole page, add the scroll offsets: rect.top + window.scrollY and rect.left + window.scrollX.
  • Border box, with transforms. The size includes padding and border. If an ancestor or the element has transform: scale(0.5) or a rotation, the result is the bounding box of the transformed shape, so width is not the CSS width.
  • Unrendered elements. An element with display: none (or one that is detached) returns all zeros.
  • Relative position. To get one element's position inside another, subtract: child.top - parent.top.
  • Snapshot. The DOMRect does not update. Call the method again after scrolling, resizing or changing styles.
  • Costs a layout. If the DOM or styles changed since the last layout, the call forces the browser to calculate layout immediately. Reading in the middle of a write loop ("layout thrashing") is slow, so read all measurements first, then write.
  • Inline elements that wrap. A single rectangle covers all lines of the text. Use getClientRects() for one rectangle per line box.
  • Not for scrolling content. For the element's scroll size, use scrollWidth and scrollHeight. For visibility changes without polling, prefer an IntersectionObserver.
  • Rounding. Values may be fractions such as 100.5. Round them with Math.round() if you compare them.

Browser support

Supported in every browser. The x and y properties are available in all current browsers.