12k
All articles

How to Auto-Size Iframes to Their Content

Auto-size iframes to their content with same-origin access, secure postMessage and Chrome frame-sizing. Compare methods and handle dynamic content with a fallback.

OpenReplay Team
OpenReplay Team
How to Auto-Size Iframes to Their Content

An iframe renders the embedded page in its own viewport and never grows to fit that page’s content, so either the parent sets a height or the embedded page reports one.

You ship a comment widget or a signup form in an iframe, and it either clips the content behind a second scrollbar or leaves a block of empty space under a short form. A session replay of a fixed-height embed shows the problem clearly: a user scrolling inside a small inner box on the parent page. A screenshot of the initial state never shows that.

This guide covers each approach in order: fixed heights, aspect-ratio, the same-origin shortcut, a secure cross-origin postMessage pair, and the frame-sizing property that Chrome 154 added, with a fallback. For framework-specific embedding, see integrating iframes with React.

Key Takeaways

  • Across origins, the parent cannot read the iframe’s document, so the embedded page must post its height with window.postMessage() to an explicit target origin.
  • A resize listener should act only after it checks event.origin against an allowlist, matches event.source to the iframe’s contentWindow, and validates the height as a finite, non-negative number.
  • ResizeObserver on document.documentElement catches height changes from images, fonts and reflow, which MutationObserver misses.
  • Chrome 154 ships frame-sizing: content-height, which needs a responsive-embedded-sizing meta tag in the embedded page’s initial HTML. Firefox and Safari don’t support it.
  • Wrap frame-sizing in @supports and keep the postMessage script running for browsers without it.
MethodOriginTracks dynamic contentChild changes needed
Fixed heightAnyNoNone
aspect-ratioAnyNo (fixed ratio only)None
Parent reads contentDocumentSame-originWith ResizeObserverNone
postMessageCross-originYesScript
frame-sizingCross-originWith requestResize()Meta tag

Fixed Height: Simple but Wrong Most of the Time

A fixed height is the only method that needs no cooperation from the embedded page. It also guarantees a mismatch whenever the content length changes. Content taller than the height gets an inner scrollbar, and shorter content leaves blank space.

.embed { width: 100%; height: 600px; border: 0; }

Use it when you can’t change the embedded page, and choose a height that fits the most common state.

Use aspect-ratio for Video Embeds

Video players scale with width rather than content, so the CSS aspect-ratio property handles them without any script:

.video-embed { width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; }

This only works for media with a known ratio. Text, forms and comment threads change height independently of width, so they need one of the methods below.

How Do You Auto-Size a Same-Origin Iframe?

When the parent and the embedded page share an origin, the parent can reach into contentDocument and read the child’s height directly. The common approach reads documentElement.scrollHeight on load. A scrollHeight reading may not drop below the frame’s current height, so measuring with getBoundingClientRect() and observing the root keeps the frame in sync as it grows and shrinks:

const frame = document.querySelector('#docs-frame');
frame.addEventListener('load', () => {
  const root = frame.contentDocument.documentElement;
  const fit = () => {
    frame.style.height = `${Math.ceil(root.getBoundingClientRect().height)}px`;
  };
  fit();
  new ResizeObserver(fit).observe(root);
});

Iframe Auto Height Across Origins With postMessage

Across origins, the same-origin policy stops the parent from reading the child’s document. The child has to measure itself and report the number with window.postMessage(). postMessage is the cross-origin method that works in every current browser.

The Child (Inside the Iframe)

<style>
  body { margin: 0; }
</style>
<script>
  const PARENT_ORIGIN = 'https://publisher.example';
  let lastHeight = 0;

  const ro = new ResizeObserver(([entry]) => {
    const box = entry.borderBoxSize && entry.borderBoxSize[0];
    const height = Math.ceil(
      box ? box.blockSize : document.documentElement.getBoundingClientRect().height
    );
    if (height === lastHeight) return;
    lastHeight = height;
    window.parent.postMessage({ type: 'resize', height }, PARENT_ORIGIN);
  });

  ro.observe(document.documentElement);
</script>

ResizeObserver fires when an element’s rendered size changes. That includes images loading, web fonts swapping in and the viewport narrowing. MutationObserver misses all of these because it only watches DOM changes. Math.ceil rounds fractional heights up, which avoids a 1px scrollbar. The second argument to postMessage() names the parent’s exact origin. If you pass "*", the message goes to whatever page has framed the child.

The Parent

<iframe id="comments" src="https://widgets.example/comments"
        title="Comments" style="width:100%; height:400px; border:0"></iframe>
<script>
  const ALLOWED_ORIGINS = new Set(['https://widgets.example']);
  const MAX_HEIGHT = 10000;
  const frame = document.getElementById('comments');

  window.addEventListener('message', (event) => {
    if (!ALLOWED_ORIGINS.has(event.origin)) return;
    if (event.source !== frame.contentWindow) return;
    const data = event.data;
    if (!data || data.type !== 'resize') return;
    const height = Number(data.height);
    if (!Number.isFinite(height) || height < 0) return;
    frame.style.height = `${Math.min(Math.ceil(height), MAX_HEIGHT)}px`;
  });
</script>

Each check in the parent’s message listener blocks a different problem:

  • Origin allowlist: other sites posting messages to your page.
  • event.source match: other frames on the same page, such as ads.
  • Type and number validation: unrelated messages, NaN and absurd heights. MAX_HEIGHT is a sanity cap you choose yourself, not a standard value.

The 400px starting height reserves space before the first message arrives, which reduces layout shift.

Measurement Pitfalls

  • Body margins. The default margin on body and margin collapsing with its first or last child can push the measured height off by the margin. Reset body { margin: 0; }.
  • height: 100% or vh on html/body. The child’s size then depends on the frame’s size, which can make the frame grow forever or never shrink.
  • Fixed or absolutely positioned overlays. They don’t add to the root’s height, so they can get clipped.

What Is frame-sizing in Chrome 154?

frame-sizing is a CSS property, added in Chrome 154, that lets an iframe take its size from the embedded document. Both sides must opt in: the parent sets the property and the child declares a meta tag. The property accepts auto, content-width, content-height, content-inline-size and content-block-size. auto keeps the default behavior.

.embed { width: 100%; max-height: 80vh; frame-sizing: content-height; }

The embedded page opts in through a responsive-embedded-sizing meta tag in its <head>:

<meta name="responsive-embedded-sizing" content="allow-origins=https://publisher.example">

allow-origins takes a space-separated list of origins. Use * only for widgets meant to be embedded anywhere. The tag must be in the initial HTML, because injecting it after load has no effect.

Under frame-sizing, the browser doesn’t watch every layout change inside the embed. After a dynamic update, the embedded page calls window.requestResize() to get a fresh measurement:

async function loadMoreComments() {
  const items = await fetchComments();
  renderComments(items);
  if ('requestResize' in window) {
    try {
      window.requestResize();
    } catch (e) {
      // Not embedded in an iframe, or the meta opt-in is missing.
    }
  }
}

Call it once after your DOM changes finish, not inside a ResizeObserver callback. It throws when the page isn’t embedded in an iframe or lacks the meta tag, so the try/catch is required. If the parent never set frame-sizing, the call doesn’t throw, but nothing resizes.

Late growth can cause layout shift that hurts Core Web Vitals, so cap the frame with max-height and reserve space for embeds above the fold. The meta tag only controls who receives size information. Control who may embed the page with CSP frame-ancestors.

The property is defined in the CSS Box Sizing Module Level 4 editor’s draft, and only Chromium implements it so far. Chrome and Edge 154 support it, while Firefox and Safari do not.

How Do You Fall Back When frame-sizing Isn’t Supported?

Use frame-sizing where the browser supports it and keep the postMessage script running elsewhere. This feature query is adapted from the Chrome post’s progressive-enhancement example, which is Apache 2.0 licensed:

.embed { width: 100%; height: 500px; }
@supports (frame-sizing: content-height) {
  .embed { height: auto; frame-sizing: content-height; }
}

As a precaution, stop the parent script from writing inline heights over native sizing. Add this guard with CSS.supports():

const nativeSizing = CSS.supports('frame-sizing', 'content-height');
// First line inside the message listener:
if (nativeSizing) return;

The child keeps both its ResizeObserver post and its feature-detected requestResize() call. @supports only confirms that the browser parses the property. Native sizing still depends on the meta tag being in the child’s initial HTML, so only use the guard for embeds whose child pages include it.

Conclusion

To size an iframe to its content, the embedded page has to report its size. In every browser, that means a ResizeObserver in the child posting to an exact origin, and a parent that checks the origin, the source and the number before setting a height. Add the responsive-embedded-sizing meta tag to your embedded pages and wrap frame-sizing in @supports. Chrome and Edge will then size the frame natively, and the postMessage pair keeps working in Firefox and Safari.

FAQs

Can I auto-size a cross-origin iframe if I cannot edit the embedded page?

No. The same-origin policy stops the parent from reading a cross-origin document, so the embedded page has to cooperate. It can either run a script that posts its height with postMessage or include the responsive-embedded-sizing meta tag for frame-sizing. Without either, the only option is a fixed height or, for video, an aspect-ratio that matches the player.

Why does my origin check reject messages from a sandboxed iframe?

An iframe with the sandbox attribute but without allow-same-origin gets an opaque origin, and its messages arrive with event.origin set to the string 'null'. Do not add 'null' to the allowlist, because every opaque origin serializes the same way. Add allow-same-origin so the frame keeps its real origin, or accept the message only when event.source matches the iframe's contentWindow.

Does postMessage resizing work with loading='lazy' iframes?

Yes, but no resize message arrives until the browser loads the frame, which for loading='lazy' happens as the iframe nears the viewport. Until then the iframe keeps whatever height the parent CSS gives it. Set a realistic starting height so the page does not jump when the first measurement arrives, and keep the listener registered before the frame loads.

What happens to the resize script when the user navigates inside the iframe?

A full navigation inside the iframe loads a new document, and the old document's ResizeObserver goes away with it. Every page that can load in the frame needs its own copy of the child script, or the frame keeps the last reported height. The parent listener survives because it lives in the parent page, and contentWindow still refers to the same frame.

Understand every bug

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — self-hosted, with full data ownership.

Star on GitHub

We use cookies to improve your experience. By using our site, you accept cookies.