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?
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>
Have you tried height="100%"
in the definition of your iframe ? It seems to do what you seek, if you add height:100%
in the css for "body" (if you do not, 100% will be "100% of your content").
EDIT: do not do this. The height
attribute (as well as the width
one) must have an integer as value, not a string.
I've found this to work the best across all browsers and devices (PC, tables & mobile).
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>