Auto-resize iframes with JavaScript for smooth, scroll-free, responsive embedded content.
Embedding content using an <iframe> It is a common technique in modern web development—from embedding forms, tools, and dashboards to entire pages. But fixed-height iframes often break the user experience by causing scrollbars, clipping content, or leaving excessive white space.
In this post, we’ll show you how to automatically adjust an iframe’s height based on its inner content, using a lightweight JavaScript approach that works smoothly across devices and browsers.
When you embed a page or component via iframe, the parent document doesn’t automatically know how tall the iframe content is. Without manually adjusting it, this often leads to:
Auto-resizing the iframe improves usability and maintains a professional, responsive design.
Add this snippet to the iframe’s content page (the page being embedded):
<script>
function sendHeight() {
if (window.self !== window.top) {
const height = document.body.scrollHeight;
window.parent.postMessage({ type: 'setHeight', height }, '*');
}
}
window.addEventListener('load', sendHeight);
window.addEventListener('resize', sendHeight);
new MutationObserver(sendHeight).observe(document.body, { childList: true, subtree: true });
</script>This script sends the content height to the parent page anytime the content changes, loads, or resizes.
On the page embedding the iframe, add the following:
<iframe id="dynamicIframe" src="your-embedded-page.html" style="width:100%; border:0;"></iframe>
<script>
window.addEventListener('message', function(event) {
if (event.data?.type === 'setHeight' && typeof event.data.height === 'number') {
const iframe = document.getElementById('dynamicIframe');
iframe.style.height = event.data.height + 'px';
}
});
</script>This listens for messages from the iframe and dynamically adjusts its height.
If you want to apply different styles when a page is loaded in an iframe, use this:
(function() {
if (window.self !== window.top && document.referrer.startsWith(window.location.origin)) {
document.body.classList.add('embedded');
}
})();Now you can target .embedded In your CSS to hide headers, simplify UI, or adjust styles for embedded contexts.
Need help implementing iframe resizing or building responsive, embedded components for your app or website?
👨💻 We specialize in frontend development and full-stack integrations. Whether you’re working with static sites, SPAs, or custom applications, we can help you deliver clean, professional experiences.
