How to adjust the width and height of an iframe to fit with content in it HTML?


We can adjust the width and height of an iframe by using CSS to set the dimensions. This can be done by setting the width and height properties to a specific value or to a percentage of the parent container. Additionally, we can use JavaScript to dynamically adjust the dimensions based on the content within the iframe. The term iframe is short for Inline frame.

Here are the possible approaches −

Using JavaScript

You can use JavaScript to adjust the width and height of an iframe to fit its content. This can be done by getting the element of the iframe and then setting its width and height properties to the values of the content inside −

<iframe id="myiframe" src="http://example.com"></iframe>
<script>
   var iframe = document.getElementById("myiframe");
   iframe.width = iframe.contentWindow.document.body.scrollWidth;
   iframe.height = iframe.contentWindow.document.body.scrollHeight;
</script>

Using CSS

You can also use CSS to adjust the width and height of an iframe to fit its content. This can be done by setting the width and height properties of the iframe to 100% and then using the padding-bottom property to adjust the height of the iframe based on the aspect ratio of the content inside −

<iframe id="myiframe" src="http://example.com"></iframe>
<style>
   #myiframe {
      width: 100%;
      height: 100%;
   }
</style>

Using HTML

You can also use HTML to adjust the width and height of an iframe to fit its content. This can be done by setting the width and height attributes of the iframe element to 100% −

<iframe width="100%" height="100%" src="http://example.com"></iframe>

Note − Keep in mind that when using JavaScript or CSS to adjust the size of an iframe, it can cause issues with cross-domain iframes as the browser may block access to the content inside the iframe. It is recommended to use the HTML method in this case.

Example

Here is a full working example of using JavaScript to adjust the width and height of an iframe to fit its content −

<!DOCTYPE html>
<html>
   <head>
      <script>
         window.onload = function() {
            var iframe = document.getElementById("myiframe");
            iframe.width = iframe.contentWindow.document.body.scrollWidth;
            iframe.height = iframe.contentWindow.document.body.scrollHeight;
         }
      </script>
   </head>
   <body>
      <iframe id="myiframe" src="https://wikipedia.org/wiki/Main_Page"></iframe>
   </body>
</html>

Updated on: 02-Sep-2023

64K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements