Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust width and height of iframe to fit with content in it

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.

like image 458
StoneHeart Avatar asked May 04 '09 09:05

StoneHeart


People also ask

How do I make content fit in 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.

How do I control the size of an 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."

How can set width and height of 100 in iframe?

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.


2 Answers

<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> 
like image 140
Ahmy Avatar answered Sep 21 '22 06:09

Ahmy


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>
like image 39
Guy Avatar answered Sep 21 '22 06:09

Guy