What is the Resize Observer API?
The Resize Observer API is a browser API that lets you watch for changes to an element's size. When the element's dimensions change — because the viewport resized, the content changed, or a CSS rule kicked in — your callback fires with the new dimensions.
Before Resize Observer, you had two bad options: listen to window.resize (which only fires on viewport changes, not individual elements) or poll with setInterval (which is wasteful and imprecise). Resize Observer solves both problems.
Basic usage
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log(`Element is now ${width}px × ${height}px`);
}
});
observer.observe(document.querySelector('#my-element'));
The callback receives an array of ResizeObserverEntry objects. Each entry has:
-
contentRect— the element's content box (excludes padding and border) -
borderBoxSize— size including border and padding -
contentBoxSize— same as contentRect but as a structured object -
target— the element being observed
When to use it
- Responsive components — resize a chart, canvas, or data grid when its container changes size
- Virtual scrolling — recalculate row heights when content changes
- Sticky headers — react when an element's height changes due to dynamic content
-
CSS custom properties — update a
--widthvariable so child elements can use it
Browser support
Resize Observer has broad support across all modern browsers (Chrome, Firefox, Safari, Edge). It's also polyfillable for legacy environments.
Caveats
- Callbacks fire asynchronously, after layout and before paint — they won't cause layout thrashing if you read dimensions inside the callback
- Observing too many elements can get expensive; unobserve when elements are removed from the DOM
- Avoid modifying the element's size inside the callback — this will trigger another observation and can cause loops