Resize Observer

Editor’s Draft,

More details about this document
This version:
https://drafts.csswg.org/resize-observer/
Latest published version:
https://www.w3.org/TR/resize-observer/
Previous Versions:
Feedback:
CSSWG Issues Repository
Editors:
(Igalia)
(Mozilla)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This specification describes an API for observing changes to Element’s size.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, etc.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Please send feedback by filing issues in GitHub (preferred), including the spec code “resize-observer” in the title, like this: “[resize-observer] …summary of comment…”. All issues and comments are archived. Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.

This document is governed by the 03 November 2023 W3C Process Document.

1. Introduction

This section is non-normative.

Responsive Web Components need to respond to Element's size changes. An example is an Element that displays a map:

Responsive Web Applications can already respond to viewport size changes. This is done with CSS media queries, or Window's resize event.

The ResizeObserver API is an interface for observing changes to Element’s size. It is an Element's counterpart to Window's resize event.

ResizeObserver’s notifications can be used to respond to changes in Element's size. Some interesting facts about these observations:

<canvas id="ellipse" style="display:block"></canvas>
<div id="menu" style="display:block;width:100px">
    <img src="hamburger.jpg" style="width:24px;height:24px">
    <p class="title">menu title</p>
</div>
// In response to resize, paint an ellipse inside a canvas
document.querySelector('#ellipse').handleResize = entry => {
    entry.target.width = entry.borderBoxSize[0].inlineSize;
    entry.target.height = entry.borderBoxSize[0].blockSize;
    let rx = Math.floor(entry.target.width / 2);
    let ry = Math.floor(entry.target.height / 2);
    let ctx = entry.target.getContext('2d');
    ctx.beginPath();
    ctx.ellipse(rx, ry, rx, ry, 0, 0, 2 * Math.PI);
    ctx.stroke();
}

// In response to resize, change title visibility depending on width
document.querySelector('#menu').handleResize = entry => {
    let title = entry.target.querySelector('.title');
    if (entry.borderBoxSize[0].inlineSize < 40)
        title.style.display = 'none';
    else
        title.style.display = 'inline-block';
}

let ro = new ResizeObserver(entries => {
  for (let entry of entries) {
    let cs = window.getComputedStyle(entry.target);
    console.log('watching element:', entry.target);
    console.log(entry.contentRect.top, ' is ', cs.paddingTop);
    console.log(entry.contentRect.left, ' is ', cs.paddingLeft);
    console.log(entry.borderBoxSize[0].inlineSize, ' is ', cs.width);
    console.log(entry.borderBoxSize[0].blockSize, ' is ', cs.height);
    if (entry.target.handleResize)
        entry.target.handleResize(entry);
  }
});

ro.observe(document.querySelector('#ellipse'));
ro.observe(document.querySelector('#menu'));

2. Resize Observer API

2.1. ResizeObserver interface

The ResizeObserver interface is used to observe changes to Element's size.

It is modeled after MutationObserver and IntersectionObserver.

enum ResizeObserverBoxOptions {
    "border-box", "content-box", "device-pixel-content-box"
};

ResizeObserver can observe different kinds of CSS sizes:

The device-pixel-content-box can be approximated by multiplying devicePixelRatio by the content-box size. However, due to browser-specific subpixel snapping behavior, authors cannot determine the correct way to round this scaled content-box size. How a UA computes the device pixel box for an element is implementation-dependent. One possible implementation could be to multiply the box size and position by the device pixel ratio, then round both the resulting floating-point size and position of the box to integer values, in a way that maximizes the quality of the rendered output.

Note that this size can be affected by position changes to the target, and thus is typically more expensive to observe than the other sizes.

dictionary ResizeObserverOptions {
    ResizeObserverBoxOptions box = "content-box";
};

This section is non-normative. An author may desire to observe more than one CSS box. In this case, author will need to use multiple ResizeObservers.

// Observe the content-box
ro.observe(document.querySelector('#menu'), { box: 'content-box' });

// Observe just the border box. Replaces previous observation.
ro1.observe(document.querySelector('#menu'), { box: 'border-box' });

This does not have any impact on which box dimensions are returned to the defined callback when the event is fired, it solely defines which box the author wishes to observe layout changes on.

[Exposed=(Window)]
interface ResizeObserver {
    constructor(ResizeObserverCallback callback);
    undefined observe(Element target, optional ResizeObserverOptions options = {});
    undefined unobserve(Element target);
    undefined disconnect();
};
new ResizeObserver(callback)
  1. Let this be a new ResizeObserver object.

  2. Set this.[[callback]] internal slot to callback.

  3. Set this.[[observationTargets]] internal slot to an empty list.

  4. Add this to Document.[[resizeObservers]] slot.

observe(target, options)

Adds target to the list of observed elements.

  1. If target is in [[observationTargets]] slot, call unobserve() with argument target.

  2. Let observedBox be the value of the box dictionary member of options.

  3. Let resizeObservation be new ResizeObservation(target, observedBox).

  4. Add the resizeObservation to the [[observationTargets]] slot.

unobserve(target)

Removes target from the list of observed elements.

  1. Let observation be ResizeObservation in [[observationTargets]] whose target slot is target.

  2. If observation is not found, return.

  3. Remove observation from [[observationTargets]].

disconnect()
  1. Clear the [[observationTargets]] list.

  2. Clear the [[activeTargets]] list.

2.2. ResizeObserverCallback

callback ResizeObserverCallback = undefined (sequence<ResizeObserverEntry> entries, ResizeObserver observer);

This callback delivers ResizeObserver's notifications. It is invoked by a broadcast active resize observations algorithm.

2.3. ResizeObserverEntry

[Exposed=Window]
interface ResizeObserverEntry {
    readonly attribute Element target;
    readonly attribute DOMRectReadOnly contentRect;
    readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize;
    readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize;
    readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize;
};

contentRect is from the incubation phase of ResizeObserver and is only included for current web compat reasons. It may be deprecated in future levels.

target, of type Element, readonly

The Element whose size has changed.

contentRect, of type DOMRectReadOnly, readonly

Element's content rect when ResizeObserverCallback is invoked.

borderBoxSize, of type FrozenArray<ResizeObserverSize>, readonly

A FrozenArray containing the Element's border box size when ResizeObserverCallback is invoked.

contentBoxSize, of type FrozenArray<ResizeObserverSize>, readonly

A FrozenArray containing the Element's content rect size when ResizeObserverCallback is invoked.

devicePixelContentBoxSize, of type FrozenArray<ResizeObserverSize>, readonly

A FrozenArray containing the Element's content rect size in integral device pixels when ResizeObserverCallback is invoked.

The box size properties are exposed as FrozenArray in order to support elements that have multiple fragments, which occur in multi-column scenarios. However the current definitions of content rect and border box do not mention how those boxes are affected by multi-column layout. In this spec, there will only be a single ResizeObserverSize returned in the FrozenArray, which will correspond to the dimensions of the first column. A future version of this spec will extend the returned FrozenArray to contain the per-fragment size information.

[Exposed=Window]
interface ResizeObserverSize {
    readonly attribute unrestricted double inlineSize;
    readonly attribute unrestricted double blockSize;
};

3. Processing Model

3.1. ResizeObservation example struct

This section is non-normative. ResizeObservation is an example struct that can be used in implementation of Resize Observer. It is being included here in order to help provide clarity during the processing model. It effectively holds observation information for a single Element. This interface is not visible to Javascript.

interface ResizeObservation {
    constructor(Element target, ResizeObserverBoxOptions observedBox);
    readonly attribute Element target;
    readonly attribute ResizeObserverBoxOptions observedBox;
    readonly attribute FrozenArray<ResizeObserverSize> lastReportedSizes;
};
target, of type Element, readonly

The observed Element.

observedBox, of type ResizeObserverBoxOptions, readonly

Which box is being observed.

lastReportedSizes, of type FrozenArray<ResizeObserverSize>, readonly

Ordered array of last reported sizes.

new ResizeObservation(target, observedBox)
  1. Let this be a new ResizeObservation object.

  2. Set this internal target slot to target.

  3. Set this internal observedBox slot to observedBox.

  4. Set this internal lastReportedSizes slot to [(0,0)].

isActive()
  1. Set currentSize by calculate box size given target and observedBox.

  2. Return true if currentSize is not equal to the first entry in this.lastReportedSizes.

  3. Return false.

3.2. Internal Slot Definitions

3.2.1. Document

Document has a [[resizeObservers]] slot that is a list of ResizeObservers in this document. It is initialized to empty.

3.2.2. ResizeObserver

ResizeObserver has a [[callback]] slot, initialized by constructor.

ResizeObserver has an [[observationTargets]] slot, which is a list of ResizeObservations. It represents all Elements being observed.

ResizeObserver has a [[activeTargets]] slot, which is a list of ResizeObservations. It represents all Elements whose size has changed since last observation broadcast that are eligible for broadcast.

ResizeObserver has a [[skippedTargets]] slot, which is a list of ResizeObservations. It represents all Elements whose size has changed since last observation broadcast that are not eligible for broadcast

3.3. CSS Definitions

3.3.1. content rect

DOM content rect is a rect whose:

content width spec does not mention how multi-column layout affects content box. In this spec, content width of an Element inside multi-column is the result of getComputedStyle(element).width. This currently evaluates to width of the first column.

Having content rect position be padding-top/left is useful for absolute positioning of target’s children. Absolute position coordinate space origin is topLeft of the padding rect.

Watching content rect means that:

Web content can also contain SVG elements. SVG elements that do not have associated CSS layout boxes define bounding box instead of a content box. Content rect for the SVGGraphicsElements without CSS layout boxes is a rect whose:

3.4. Algorithms

3.4.1. Gather active resize observations at depth

It computes all active resize observations for a document. To gather active resize observations at depth, run these steps:

  1. Let depth be the depth passed in.

  2. For each observer in [[resizeObservers]] run these steps:

    1. Clear observer’s [[activeTargets]], and [[skippedTargets]].

    2. For each observation in observer.[[observationTargets]] run this step:

      1. If observation.isActive() is true

        1. Let targetDepth be result of calculate depth for node for observation.target.

        2. If targetDepth is greater than depth then add observation to [[activeTargets]].

        3. Else add observation to [[skippedTargets]].

3.4.2. Has active resize observations

To determine if Document has active resize observations run these steps:

  1. For each observer in [[resizeObservers]] run this step:

    1. If observer.[[activeTargets]] is not empty, return true.

  2. return false.

3.4.3. Has skipped resize observations

To determine if Document has skipped resize observations run these steps:

  1. For each observer in [[resizeObservers]] run this step:

    1. If observer.[[skippedTargets]] is not empty, return true.

  2. return false.

3.4.4. Create and populate a ResizeObserverEntry

To create and populate a ResizeObserverEntry for a given target, run these steps:
  1. Let this be a new ResizeObserverEntry.

  2. Set this.target slot to target.

  3. Set this.borderBoxSize slot to result of calculating box size given target and observedBox of "border-box".

  4. Set this.contentBoxSize slot to result of calculating box size given target and observedBox of "content-box".

  5. Set this.devicePixelContentBoxSize slot to result of calculating box size given target and observedBox of "device-pixel-content-box".

  6. Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".

  7. If target is not an SVG element or target is an SVG element with an associated CSS layout box do these steps:

    1. Set this.contentRect.top to target.padding top.

    2. Set this.contentRect.left to target.padding left.

  8. If target is an SVG element without an associated CSS layout box do these steps:

    1. Set this.contentRect.top and this.contentRect.left to 0.

3.4.5. Broadcast active resize observations

broadcast active resize observations delivers all active resize observations in a document, and returns the depth of the shallowest broadcast target depth.

To broadcast active resize observations for a document, run these steps:

  1. Let shallowestTargetDepth be ∞

  2. For each observer in document.[[resizeObservers]] run these steps:

    1. If observer.[[activeTargets]] slot is empty, continue.

    2. Let entries be an empty list of ResizeObserverEntryies.

    3. For each observation in [[activeTargets]] perform these steps:

      1. Let entry be the result of running create and populate a ResizeObserverEntry given observation.target.

      2. Add entry to entries.

      3. Set observation.lastReportedSizes to matching entry sizes.

        1. Matching sizes are entry.borderBoxSize if observation.observedBox is "border-box"

        2. Matching sizes are entry.contentBoxSize if observation.observedBox is "content-box"

        3. Matching sizes are entry.devicePixelContentBoxSize if observation.observedBox is "device-pixel-content-box"

      4. Set targetDepth to the result of calculate depth for node for observation.target.

      5. Set shallowestTargetDepth to targetDepth if targetDepth < shallowestTargetDepth

    4. Invoke observer.[[callback]] with entries.

    5. Clear observer.[[activeTargets]].

  3. Return shallowestTargetDepth.

3.4.6. Deliver Resize Loop Error

To deliver resize loop error notification run these steps:

  1. Create a new ErrorEvent.

  2. Initialize event’s message slot to "ResizeObserver loop completed with undelivered notifications.".

  3. Report the exception event.

3.4.7. Calculate depth for node

To calculate depth for node, given a node, run these steps:

  1. Let p be the parent-traversal path from node to a root Element of this element’s flattened DOM tree.

  2. Return number of nodes in p.

3.4.8. Calculate box size, given target and observed box

This algorithm computes target Element's observed box size. Type of box is described by ResizeObserverBoxOptions. The SVG elements which don’t have associated CSS layout boxes are an exception. The sizes of these elements are always their bounding box sizes, because these elements do not use standard CSS box model.

To calculate box size, given target and observedBox, run these steps:

  1. Let computedSize be a new ResizeObserverSize object.

  2. If target is an SVGGraphicsElement that does not have an associated CSS layout box:

    If observedBox is "border-box"
    If observedBox is "content-box"
    1. Set computedSize’s inlineSize attribute to target’s bounding box inline length.

    2. Set computedSize’s blockSize attribute to target’s bounding box block length.

    If observedBox is "device-pixel-content-box"
    1. Set computedSize’s inlineSize attribute to target’s bounding box inline length, in integral device pixels.

    2. Set computedSize’s blockSize attribute to target’s bounding box block length, in integral device pixels.

  3. Otherwise:

    If observedBox is "border-box"
    1. Set computedSize’s inlineSize attribute to target’s border area inline length.

    2. Set computedSize’s blockSize attribute to target’s border area block length.

    If observedBox is "content-box"
    1. Set computedSize’s inlineSize attribute to target’s content area inline length.

    2. Set computedSize’s blockSize attribute to target’s content area block length.

    If observedBox is "device-pixel-content-box"
    1. Set computedSize’s inlineSize attribute to target’s content area inline length, in integral device pixels.

    2. Set computedSize’s blockSize attribute to target’s content area block length, in integral device pixels.

  4. Return computedSize.

3.5. ResizeObserver Lifetime

A ResizeObserver will remain alive until both of these conditions are met:

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Tests

Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.


Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Partial implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported component values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-BOX-4]
Elika Etemad. CSS Box Model Module Level 4. URL: https://drafts.csswg.org/css-box-4/
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. URL: https://drafts.csswg.org/css2/
[CSSOM-VIEW-1]
Simon Pieters. CSSOM View Module. URL: https://drafts.csswg.org/cssom-view/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[GEOMETRY-1]
Simon Pieters; Chris Harrelson. Geometry Interfaces Module Level 1. URL: https://drafts.fxtf.org/geometry/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[SVG2]
Amelia Bellamy-Royds; et al. Scalable Vector Graphics (SVG) 2. URL: https://svgwg.org/svg2-draft/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

IDL Index

enum ResizeObserverBoxOptions {
    "border-box", "content-box", "device-pixel-content-box"
};

dictionary ResizeObserverOptions {
    ResizeObserverBoxOptions box = "content-box";
};

[Exposed=(Window)]
interface ResizeObserver {
    constructor(ResizeObserverCallback callback);
    undefined observe(Element target, optional ResizeObserverOptions options = {});
    undefined unobserve(Element target);
    undefined disconnect();
};

callback ResizeObserverCallback = undefined (sequence<ResizeObserverEntry> entries, ResizeObserver observer);

[Exposed=Window]
interface ResizeObserverEntry {
    readonly attribute Element target;
    readonly attribute DOMRectReadOnly contentRect;
    readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize;
    readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize;
    readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize;
};

[Exposed=Window]
interface ResizeObserverSize {
    readonly attribute unrestricted double inlineSize;
    readonly attribute unrestricted double blockSize;
};

MDN

ResizeObserver/ResizeObserver

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserver/disconnect

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserver/observe

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserver/unobserve

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserver

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverEntry/borderBoxSize

In all current engines.

Firefox92+Safari15.4+Chrome84+
Opera?Edge84+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverEntry/contentBoxSize

In all current engines.

Firefox92+Safari15.4+Chrome84+
Opera?Edge84+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverEntry/contentRect

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverEntry/target

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverEntry

In all current engines.

Firefox69+Safari13.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverSize/blockSize

In all current engines.

Firefox69+Safari15.4+Chrome84+
Opera?Edge84+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverSize/inlineSize

In all current engines.

Firefox69+Safari15.4+Chrome84+
Opera?Edge84+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

ResizeObserverSize

In all current engines.

Firefox69+Safari15.4+Chrome84+
Opera?Edge84+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?