Friday, September 5, 2025
HomeLanguagesJavascriptResize an iframe based on the content

Resize an iframe based on the content

The iframe HTML element is often used to insert contents from another source. Contents that need resizing are 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:

html




<!DOCTYPE html>
<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>


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 the iframe within the script tag:
    let iframe = document.getElementById(“myIframe”);
  • We Adjust the iframe height onload event by:
    iframe.onload = function(){}

html




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


Output:

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS