Codectionary / Developer documentation / JavaScript

Observing Element Sizes with ResizeObserver

ResizeObserver reports changes to an element’s box size, including changes unrelated to window resizing. It is useful for components that depend on their allocated width. Callbacks run during rendering; changing the observed dimensions in response can produce feedback loops.

Syntax

const observer = new ResizeObserver(entries => { /* inspect entries */ });
observer.observe(element);

Examples

Observing Element Sizes with ResizeObserver: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: In a browser document, the console prints 200 once, then the observer and temporary element are removed.

const box = document.createElement("div");
box.style.cssText = "width:200px;padding:10px;border:1px solid";
box.textContent = "Resize observer example";
document.body.append(box);
const observer = new ResizeObserver(([entry]) => {
  console.log(Math.round(entry.contentRect.width));
  observer.disconnect();
  box.remove();
});
observer.observe(box);
  1. Expected result: In a browser document, the console prints 200 once, then the observer and temporary element are removed.
  2. contentRect.width measures the content box, excluding the specified padding and border.
  3. disconnect stops observation when the result is no longer needed.

Best practices

  • Avoid repeatedly changing observed dimensions inside the callback.
  • Use CSS container queries when only styling depends on component size.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading