The Wayback Machine - https://web.archive.org/web/20250126171315/https://www.geeksforgeeks.org/resize-an-iframe-based-on-the-content/
Open In App

Resize an iframe based on the content

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Resizing an iframe based on the content means automatically adjusting the iframe’s height and/or width to fit the embedded content’s dimensions. This prevents scrollbars and ensures the content is fully visible without manually setting fixed iframe sizes.

Note: To open the source site to resize its contents, the source site must be listed in the same directory.

Here we have some common approaches:

Approach 1: Resizing an iframe Using Internal CSS

The approach uses a resizable container around the iframe, with fixed dimensions and resize: both to enable manual resizing. The overflow properties handle content overflow with scrollbars, while the iframe adapts to fully occupy the container space.

Example : In this example we creates a resizable <div> containing an <iframe>. The iframe takes up the full width and height of the container, while scrollbars are enabled for overflow content.

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:

Approach 2: Resizing an iframe using Javascript

The approach uses JavaScript to dynamically adjust the iframe’s height based on its content. By accessing the contentWindow property and setting the iframe’s height on the onload event, the iframe automatically resizes to fit the content without scrollbars.

Example : This example automatically resizes an iframe’s height to fit its content using JavaScript. The script adjusts the iframe height based on the document’s scroll height once the iframe has loaded.

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:



Next Article

Similar Reads

three90RightbarBannerImg