CKTIS / JavaScript
DOMRect: width and height properties
Read a rectangle’s width and height, interpret fractional and negative values, and distinguish an element’s measured bounds from its CSS size.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
rect.width
rect.height
rect.width = newWidth
rect.height = newHeightDOMRect.width/height refers to two numeric instance properties: rect.width is the width and rect.height is the height, not a position coordinate. Read them without parentheses. Both are writable on DOMRect and read-only on DOMRectReadOnly.
Dimensions can be fractional, and a rectangle you construct can also have negative dimensions. If width is negative, left is x + width; otherwise it is x. If height is negative, top is y + height; otherwise it is y. A negative sign changes the direction from (x, y), not the absolute size.
element.getBoundingClientRect() returns the rectangle enclosing the element’s nonempty border boxes, including padding and borders but not margins. Empty border boxes are ignored when nonempty boxes exist. If all the boxes are empty, the method returns a rectangle with zero width and height at the first box’s origin. Its dimensions are in CSS pixels and reflect CSS transforms, so they need not match the element’s CSS width and height values. Writing to the returned object does not change the element. Call the method again for a fresh measurement.
DOMRect is a Web API, not part of ECMAScript 2024. Availability depends on the runtime.
Examples
{
const x = 10, y = 20, width = -30.5, height = 12.25;
// Without native DOMRect, model only the geometry used in this example.
const rect = typeof globalThis.DOMRect === "function"
? new globalThis.DOMRect(x, y, width, height)
: {
x, y, width, height,
get left() {
return this.width < 0 ? this.x + this.width : this.x;
},
};
console.log(`width=${rect.width}, height=${rect.height}, left=${rect.left}`);
rect.width = 30.5;
console.log(`width=${rect.width}, height=${rect.height}, left=${rect.left}`);
}Result
width=-30.5, height=12.25, left=-20.5 width=30.5, height=12.25, left=10
Run this in a browser console to use native `DOMRect`. In Node.js without `DOMRect`, the example uses a minimal geometry model. Changing the sign of `width` moves `left` from `-20.5` to `10`; `height` stays the same.
Related lessons
- JavaScript · Lesson 35 · Intermediate · Version: 3