I need a solution for auto-adjusting the width
and height
of an iframe
to barely fit its content. The point is that the width and height can be changed after the iframe
has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
The width and height inside the embed code can be adjusted by changing the numbers between the quotation marks, shown below. The standard size of an iframe for desktop is a width of "560" and height of "315."
To get the iframe to properly use 100% the parent needs to be 100%. In newer doctypes the html and body tag are not automatically 100%. When I added height:100% for html and body then it worked flawlessly.
<script type="application/javascript"> function resizeIFrameToFitContent( iFrame ) { iFrame.width = iFrame.contentWindow.document.body.scrollWidth; iFrame.height = iFrame.contentWindow.document.body.scrollHeight; } window.addEventListener('DOMContentLoaded', function(e) { var iFrame = document.getElementById( 'iFrame1' ); resizeIFrameToFitContent( iFrame ); // or, to resize all iframes: var iframes = document.querySelectorAll("iframe"); for( var i = 0; i < iframes.length; i++) { resizeIFrameToFitContent( iframes[i] ); } } ); </script> <iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>
one-liner solution for embeds: starts with a min-size and increases to content size. no need for script tags.
<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
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