How to use the Resize Observer API
· Category: HTML & CSS
Short answer
Resize Observer reports changes to the content rectangle of an element, making it perfect for component-level responsive behavior.
Steps
- Create a
ResizeObserverwith a callback that receives entries. - Call
.observe(element)on the target. - Read
contentRectorborderBoxSizefrom the entry.
Example
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log(width, height);
}
});
ro.observe(document.querySelector('.box'));
Tips
- Use it for canvas resizing, responsive charts, and container queries fallback.
- More accurate than polling or window resize events.
- Unobserve elements when they are removed to prevent memory leaks.