A panel can become narrow because its parent changes, even when the browser window does not. ResizeObserver reports changes to an element's content box, so a reusable component can react to its own available space.

const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    entry.target.classList.toggle(
      "is-compact",
      entry.contentRect.width < 480,
    );
  }
});

observer.observe(card);

Observe only what the component needs

  • Create one observer for related elements rather than one per tiny child.
  • Stop observing removed elements or disconnect the observer when its owner is disposed.
  • Use CSS container queries when the change is purely visual and needs no JavaScript.

Avoid a resize feedback loop

Changing the observed element's own dimensions in response to every measurement can trigger another observation. Use stable thresholds and avoid setting a size that oscillates around the threshold.

Test with the component inside narrow and wide containers, not only by resizing the full browser window.