Resize an iframe based on the content

The iframe HTML element is often used to insert contents from another source. Contents which needs resizing is done indirectly using a div tag. The trick is to initiate with a div tag and enclose within an iframe tag. Now provide iframe with CSS.
Note: To open the source site to resize its contents, the source site must be listed in the same directory.

Example 1: Below is the implementation of HTML code to resize contents using Internal CSS:-

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <style>
        body {
            background-color: LIGHTGREY;
        }
          
        #target {
            width: 300px;
            height: 200px;
            overflow-y: auto;
            overflow-x: auto;
            resize: both;
            position: relative;
            z-index: 2;
        }
          
        iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>
  
</head>
  
<body>
    <div id="target">
        <iframe src="/tryit.php"></iframe>
    </div>
</body>
  
</html>

chevron_right


Output:



Here we have used an internal style sheet to fix the dimension of displaying area as width and height in pixels under target. CSS overflow property controls the contents that are too big to fit into an area.

Example 2: Below is the implementation of HTML code to resize contents, using Javascript:-
We will use JavaScript contentWindow property that will iFrame automatically adjust its height according to the contents, no scrollbars will appear.

  • We select iframe within script tag:
    var iframe = document.getElementById(“myIframe”);
  • We Adjust iframe height onload event by:
    iframe.onload = function(){}
filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <style>
        div {
            width: 50%;
        }
    </style>
</head>
  
<body>
    <iframe src="/tryit.php" id="target">
    </iframe>
    <script>
        var div = document.getElementById("target");
        div.onload = function() {
            div.style.height =
              div.contentWindow.document.body.scrollHeight + 'px';
        }
    </script>
</body>
  
</html>

chevron_right


Output:



My Personal Notes arrow_drop_up

I am computer engineer and work as content creator for various sites as freelancer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.