How to make dynamic height of iframe?

by muriel.schmidt , in category: HTML & CSS , 3 months ago

How to make dynamic height of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a month ago

@muriel.schmidt 

To make the height of an iframe dynamic, you can use JavaScript to dynamically set the height based on the content inside the iframe. Here's a step-by-step guide on how to achieve this:

  1. Add an iframe element to your HTML file with a specific ID:
1
<iframe id="myIframe" src="https://www.example.com"></iframe>


  1. Add a script tag at the bottom of your HTML file to write JavaScript code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<script>
  // Get the iframe element
  var iframe = document.getElementById('myIframe');

  // Function to set the height of the iframe dynamically based on its content
  function setIframeHeight() {
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
  }

  // Call the setIframeHeight function when the iframe content has loaded
  iframe.onload = function() {
    setIframeHeight();
  };

  // Call the setIframeHeight function whenever the window is resized
  window.onresize = function() {
    setIframeHeight();
  };
</script>


  1. With this script, the height of the iframe will adjust dynamically based on the content inside it. The setIframeHeight function sets the height of the iframe to the height of the content within it. The onload event triggers the function when the content of the iframe has loaded, and the onresize event triggers the function when the window is resized.


By following these steps, you can make the height of the iframe dynamic and adjust automatically based on the content it displays.