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);- Expected result: In a browser document, the console prints 200 once, then the observer and temporary element are removed.
- contentRect.width measures the content box, excluding the specified padding and border.
- 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