CKTIS / JavaScript
Measuring an element’s bounding rectangle height
`getBoundingClientRect()` measures an element’s geometry relative to the viewport. Read `DOMRect.height` to get the rectangle’s height in CSS pixels.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const rect = element.getBoundingClientRect();
const height = rect.height;Element.getBoundingClientRect and DOMRect.height work together: call the Element instance method element.getBoundingClientRect() with no arguments, then read rect.height without parentheses. The method returns a DOMRect based on the list from getClientRects(). If the list is empty, it returns a rectangle with x, y, width, and height all set to 0. If each rectangle in the list has zero width or zero height, it returns the first rectangle, which can still have nonzero height. Otherwise, it returns the smallest axis-aligned rectangle enclosing every rectangle with nonzero width or height, including those with just one nonzero dimension. Coordinates such as top and left are viewport-relative and can change with scrolling. Height is a dimension, not a coordinate.
rect.height is a number in CSS pixels and can be fractional. For a simple HTML element with one box, the measurement includes content, padding, and borders, but not margins. It accounts for CSS transforms, so it can differ from the CSS height and from the integer layout measurement offsetHeight. If the element generates no CSS box, as with display: none, the height is 0.
The returned rectangle is a snapshot. Measure again after a layout or transform change to get current dimensions. Assigning to rect.height changes only the DOMRect object, not the element; on DOMRectReadOnly the property is read-only.
This is a Web API, not an ECMAScript 2024 feature. Measuring an element requires a host with DOM and layout support. Check the result of querySelector() before calling the method: attempting the call on null throws a TypeError rather than returning a zero measurement.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bounding rectangle height</title>
</head>
<body>
<script>
const box = document.createElement('div');
box.style.cssText = 'box-sizing: content-box; width: 100px; height: 44px; padding: 5px; border: 0;';
document.body.append(box);
const before = box.getBoundingClientRect();
box.style.transform = 'scaleY(0.5)';
console.log(before.height);
console.log(box.getBoundingClientRect().height);
box.remove();
</script>
</body>
</html>Result
54 27
Save the example as an HTML file, open it in a browser, and check the developer-tools console. The saved rectangle reports `54`; after `scaleY(0.5)`, a fresh measurement reports `27`.
Related lessons
- JavaScript · Lesson 11 · Advanced · Version: 4