How to adjust the height of iframe based on the loaded content using jQuery?

To adjust the height of iframe based on the loaded content, use the jQuery height() method. This is particularly useful when you want to dynamically resize iframes to fit their content or respond to user interactions.

Basic Height Adjustment

The simplest approach is to set a fixed height value using jQuery. You can try to run the following code to adjust height of iframe dynamically on button click −

Example

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("button").click(function(){
               $("iframe").height(300);
            });
         });
      </script>
   </head>
   <body>
      <iframe src="https://www.qries.com" style="height:150px;width:400px;border:2px solid gray;background-color:lightblue;"></iframe>
      <br><br>
      <button>Change Height</button>
   </body>
</html>

Auto-Adjusting Height Based on Content

For same-domain content, you can automatically adjust the iframe height based on its loaded content −

Example

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("#autoResize").on("load", function(){
               var iframe = $(this);
               try {
                  var iframeContent = iframe.contents();
                  var contentHeight = iframeContent.find('body').outerHeight();
                  iframe.height(contentHeight + 20); // Add some padding
               } catch(e) {
                  // Cross-domain restrictions - fallback to fixed height
                  iframe.height(400);
               }
            });
            
            $("#manualResize").click(function(){
               $("#autoResize").height(250);
            });
         });
      </script>
   </head>
   <body>
      <p><b>Note:</b> Auto-resize works only for same-domain content due to browser security restrictions.</p>
      <iframe id="autoResize" src="data:text/html,<html><body style='margin:0;padding:20px;'><h2>Sample Content</h2><p>This iframe will auto-adjust its height.</p><p>Additional content here...</p></body></html>" 
              style="width:100%;border:1px solid #ccc;"></iframe>
      <br><br>
      <button id="manualResize">Set Manual Height</button>
   </body>
</html>

The height() method accepts pixel values, and when combined with the iframe's load event, you can create responsive iframe layouts that adjust automatically to their content.

Updated on: 2026-03-13T20:50:23+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements