Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMRect: top edge (`top`) and height (`height`)

`top` tells you where the rectangle’s upper edge is; `height` tells you its signed height. The two properties answer different questions whether you create a rectangle or measure an element.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

rect.top
rect.height
new DOMRect(x, y, width, height)
element.getBoundingClientRect()

DOMRect.top/height refers to two instance properties, not methods: rect.top is the vertical coordinate of the upper edge, and rect.height is the signed height, not a coordinate. Both are numbers and can have fractional values.

For finite y and height, top is y + height when height < 0, and y otherwise. A negative height in a manually constructed rectangle stays negative; it is not converted to an absolute value. On a DOMRect, you can assign to height, and reading top reflects the change. top is read-only on both interfaces; height is also read-only on DOMRectReadOnly.

For a result from element.getBoundingClientRect(), both values are in CSS pixels. top is relative to the top of the viewport and can be negative if the rectangle’s upper edge is above it. height is the nonnegative height of the bounding rectangle, which accounts for padding and borders, not just content. The result does not update automatically: call the method again after scrolling or a layout change to get a fresh measurement. Editing the returned rectangle does not change the element.

DOMRect is a Web API, not part of ECMAScript 2024. Do not assume it is available in every JavaScript runtime.

Examples

{
  const y = 20;
  const height = 8;

  // Without DOMRect, model only top and signed height for finite values.
  const rect = typeof DOMRect === "function"
    ? new DOMRect(0, y, 10, height)
    : {
        y,
        height,
        get top() {
          return this.height < 0 ? this.y + this.height : this.y;
        },
      };

  console.log(`top=${rect.top}, height=${rect.height}`);

  rect.height = -8;
  console.log(`top=${rect.top}, height=${rect.height}`);
}

Result

top=20, height=8
top=12, height=-8

The example needs no page element. `y` stays at `20`, but after assigning `height = -8`, the upper edge is at `12`.

Related lessons

  • JavaScript · Lesson 34 · Intermediate · Version: 3

Sources