How should I set the dimensions of an iframe dynamically, so the size is flexible for different viewport sizes?
For example:
<iframe src="html_intro.asp" width="100%" height="300"> <p>Hi SOF</p> </iframe>
In this case the height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window.
At any size, the iframe aspect ratio should be the same. How can this be done?
Answer: Use the contentWindow Property You can use the JavaScript contentWindow property to make an iFrame automatically adjust its height according to the contents inside it, so that no vertical scrollbar will appear.
Next, we put the <iframe> inside this box, making it fill the whole box. To size the <iframe> , we ignore the width="560" height="315" element properties, and instead use the CSS properties width:100%;height:100%; . That's it: a full-width <iframe> with fixed aspect ratio. Enjoy.
The iframe itself ('the box') can be responsive. But everything inside the iframe is a separate page, and therefore not in the domain of your CSS nor JS.
If you use jquery, it can be done by using $(window).height();
<iframe src="html_intro.asp" width="100%" class="myIframe"> <p>Hi SOF</p> </iframe> <script type="text/javascript" language="javascript"> $('.myIframe').css('height', $(window).height()+'px'); </script>
Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.
<style> #myFrame { width:100%; height:100%; } </style> <iframe src="html_intro.asp" id="myFrame"> <p>Hi SOF</p> </iframe>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With