How to set iframe size dynamically
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 wind开发者_JS百科ow 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>
Latest css rules will allow you to do use viewport directly, like so:
<iframe src="html_intro.asp" width="100vw" height="50vh">
<p>Hi SOF</p>
</iframe>
I personally like to adjust for iframes
by manipulating their parent containers:
<div class='iframe-parent'>
<iframe src="html_intro.asp">
<p>Hi SOF</p>
</iframe>
</div>
Now the css:
.iframe-parent{
width: 100vw;
height: 50vh;
}
/* Expand to the entire container */
iframe{
width: 100%;
height: 100%;
}
The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window
<!DOCTYPE html>
<html>
<body>
<center><h2>Heading</h2></center>
<center><p>Paragraph</p></center>
<iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
</body>
</html>
精彩评论