SyntaxStudy
Sign Up
HTML Dynamic iframe Height
HTML Advanced 6 min read

Dynamic iframe Height

Auto iframe Height

Automatically resizing an iframe to match its content height requires postMessage communication between the child and parent pages. The child sends its scrollHeight; the parent sets the iframe height.

Example
// Inside the iframe (child.html)
window.addEventListener("load", () => {
  const height = document.body.scrollHeight;
  window.parent.postMessage({ iframeHeight: height }, "*");
});

// In the parent page
window.addEventListener("message", (event) => {
  const iframe = document.querySelector("iframe");
  if (event.data.iframeHeight) {
    iframe.style.height = event.data.iframeHeight + "px";
  }
});
Pro Tip

Use a ResizeObserver in the child frame to detect content size changes and send updates continuously.