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

  1. Create a ResizeObserver with a callback that receives entries.
  2. Call .observe(element) on the target.
  3. Read contentRect or borderBoxSize from 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.