How to make an iframe responsive, without assuming an aspect ratio? For example, the content may have any width or height, which is unknown before rendering.
Note, you can use Javascript.
Example:
<div id="iframe-container">
<iframe/>
</div>
Size this iframe-container
so that contents of it barely fit inside without extra space, in other words, there is enough space for content so it can be shown without scrolling, but no excess space. Container wraps the iframe perfectly.
This shows how to make an iframe responsive, assuming the aspect ratio of the content is 16:9. But in this question, the aspect ratio is variable.
A responsive iframe will render well across a variety of devices and screen sizes. In order to make your embedded iframe responsive, you need to wrap the iframe in a div and apply inline css.
Historically, making iframes responsive required you to wrap the iframe in a container div . Position the iframe in the top left corner of the div . Make it 100% of the height and width of the div . Add padding to the top of the div equal to the aspect ratio of the iframe (for HD videos, 56.25% , or 9 / 16 * 100 ).
In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
Unlike <img> s, <iframe> s don't have a fixed aspect ratio, because <iframe> s embed web pages, which don't have fixed/known aspect ratios. But for the particular case of YouTube videos, there is a fixed aspect ratio we want: the standard <iframe> has width="560" height="315" , which simplifies to a 16:9 aspect ratio.
It is not possible to interact with a different origin iFrame using Javascript so to get the size of it; the only way to do it is by using window.postMessage
with the targetOrigin
set to your domain or the wildchar *
from iFrame source. You can proxy the contents of the different origin sites and use srcdoc
, but that is considered a hack and it won't work with SPAs and many other more dynamic pages.
Suppose we have two same origin iFrames, one of short height and fixed width:
<!-- iframe-short.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
body {
width: 300px;
}
</style>
</head>
<body>
<div>This is an iFrame</div>
<span id="val">(val)</span>
</body>
and a long height iFrame:
<!-- iframe-long.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
#expander {
height: 1200px;
}
</style>
</head>
<body>
<div>This is a long height iFrame Start</div>
<span id="val">(val)</span>
<div id="expander"></div>
<div>This is a long height iFrame End</div>
<span id="val">(val)</span>
</body>
We can get iFrame size on load
event using iframe.contentWindow.document
that we'll send to the parent window using postMessage
:
<div>
<iframe id="iframe-local" src="iframe-short.html"></iframe>
</div>
<div>
<iframe id="iframe-long" src="iframe-long.html"></iframe>
</div>
<script>
function iframeLoad() {
window.top.postMessage({
iframeWidth: this.contentWindow.document.body.scrollWidth,
iframeHeight: this.contentWindow.document.body.scrollHeight,
params: {
id: this.getAttribute('id')
}
});
}
window.addEventListener('message', ({
data: {
iframeWidth,
iframeHeight,
params: {
id
} = {}
}
}) => {
// We add 6 pixels because we have "border-width: 3px" for all the iframes
if (iframeWidth) {
document.getElementById(id).style.width = `${iframeWidth + 6}px`;
}
if (iframeHeight) {
document.getElementById(id).style.height = `${iframeHeight + 6}px`;
}
}, false);
document.getElementById('iframe-local').addEventListener('load', iframeLoad);
document.getElementById('iframe-long').addEventListener('load', iframeLoad);
</script>
We'll get proper width and height for both iFrames; you can check it online here and see the screenshot here.
The method described here is a hack and it should be used if it's absolutely necessary and there is no other way around; it won't work for most dynamic generated pages and SPAs. The method fetches the page HTML source code using a proxy to bypass CORS policy (cors-anywhere
is an easy way to create a simple CORS proxy server and it has an online demo https://cors-anywhere.herokuapp.com
) it then injects JS code to that HTML to use postMessage
and send the size of the iFrame to the parent document. It even handles iFrame resize
(combined with iFrame width: 100%
) event and posts the iFrame size back to the parent.
patchIframeHtml
:A function to patch the iFrame HTML code and inject custom Javascript that will use postMessage
to send the iFrame size to the parent on load
and on resize
. If there is a value for the origin
parameter, then an HTML <base/>
element will be prepended to the head using that origin URL, thus, HTML URIs like /some/resource/file.ext
will get fetched properly by the origin URL inside the iFrame.
function patchIframeHtml(html, origin, params = {}) {
// Create a DOM parser
const parser = new DOMParser();
// Create a document parsing the HTML as "text/html"
const doc = parser.parseFromString(html, 'text/html');
// Create the script element that will be injected to the iFrame
const script = doc.createElement('script');
// Set the script code
script.textContent = `
window.addEventListener('load', () => {
// Set iFrame document "height: auto" and "overlow-y: auto",
// so to get auto height. We set "overlow-y: auto" for demontration
// and in usage it should be "overlow-y: hidden"
document.body.style.height = 'auto';
document.body.style.overflowY = 'auto';
poseResizeMessage();
});
window.addEventListener('resize', poseResizeMessage);
function poseResizeMessage() {
window.top.postMessage({
// iframeWidth: document.body.scrollWidth,
iframeHeight: document.body.scrollHeight,
// pass the params as encoded URI JSON string
// and decode them back inside iFrame
params: JSON.parse(decodeURIComponent('${encodeURIComponent(JSON.stringify(params))}'))
}, '*');
}
`;
// Append the custom script element to the iFrame body
doc.body.appendChild(script);
// If we have an origin URL,
// create a base tag using that origin
// and prepend it to the head
if (origin) {
const base = doc.createElement('base');
base.setAttribute('href', origin);
doc.head.prepend(base);
}
// Return the document altered HTML that contains the injected script
return doc.documentElement.outerHTML;
}
getIframeHtml
:A function to get a page HTML bypassing the CORS using a proxy if useProxy
param is set. There can be additional parameters that will be passed to the postMessage
when sending size data.
function getIframeHtml(url, useProxy = false, params = {}) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
// If we use a proxy,
// set the origin so it will be placed on a base tag inside iFrame head
let origin = useProxy && (new URL(url)).origin;
const patchedHtml = patchIframeHtml(xhr.responseText, origin, params);
resolve(patchedHtml);
}
}
// Use cors-anywhere proxy if useProxy is set
xhr.open('GET', useProxy ? `https://cors-anywhere.herokuapp.com/${url}` : url, true);
xhr.send();
});
}
The message event handler function is exactly the same as in "Same origin iFrame size".
We can now load a cross origin domain inside an iFrame with our custom JS code injected:
<!-- It's important that the iFrame must have a 100% width
for the resize event to work -->
<iframe id="iframe-cross" style="width: 100%"></iframe>
<script>
window.addEventListener('DOMContentLoaded', async () => {
const crossDomainHtml = await getIframeHtml(
'https://en.wikipedia.org/wiki/HTML', true /* useProxy */, { id: 'iframe-cross' }
);
// We use srcdoc attribute to set the iFrame HTML instead of a src URL
document.getElementById('iframe-cross').setAttribute('srcdoc', crossDomainHtml);
});
</script>
And we'll get the iFrame to size to it's contents full height without any vertical scrolling even using overflow-y: auto
for the iFrame body (it should be overflow-y: hidden
so we don't get scrollbar flickering on resize).
You can check it online here.
Again to notice that this is a hack and it should be avoided; we cannot access Cross-Origin iFrame document nor inject any kind of things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With