Reputation: 95
Is there a way to fit height of iframe to it's content? Would you show me how to do it? I tried searching and trying out the codes on the net but no luck
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta NAME="Description" content="Communigate Technologies" />
<meta HTTP-EQUIV="Cache-Control" content="no-cache" />
<meta HTTP-EQUIV="pragma" content="no-cache" />
<title></title>
</head>
<body>
<div align="center" style="z-index:1;">
<?php include 'header.html' ?>
<iframe align=top width=800px src="aboutus1.php" frameborder=1 border=0 framespacing=0 SCROLLING=no id="bodyframeid" name="bodyframename"></iframe>
</div>
</body>
</html>
Upvotes: 5
Views: 5779
Reputation: 11
I do it this way:
document.getElementById("iframename").height = (document.getElementById("iframename").contentWindow.document.body.scrollHeight) + "px";
Sometimes this didn't work but I noticed it was because the page of the iframe wasn't completelly rendered. In this case, and I never noticed any further problem, put the instruction inside:
setTimeout(function (){ - here - }, 100)
Hope I helped.
Upvotes: 1
Reputation: 770
Since we are in the age of CSS3, you can do this by using viewport units. These units allow you to specify sizes in terms of percentages of the viewport width and viewport height. This is the user's viewport, also known as screen. However, in all major browsers I've tried it, if you put an iframe inside a div, which is inside another div and positioned relative, the viewport units are relative to this div. And since 100 viewport height units mean 100% height, you can do like this:
<div id="parent">
<div id="wrapper" style="position:relative">
<iframe style="position:absolute;top:0px;width:100%;height:100vh;" src="http://anydomain.com"></iframe>
</div>
</div>
I find this to be the best solution possible, since it is cross-domain, and displays exactly like you want it without any javascript or other complex stuff.
And most importantly, it works on all browsers, even mobile ones (tested on android and iphone)!
Upvotes: 7
Reputation: 1225
If you have the same origin for document and iframe content (and in your example, you have) you can run from your main document:
var iframe = document.getElementById('my-iframe')
var content = iframe.contentWindow.document.getElementById('content')
var height = content.offsetHeight + 15 //add something to support paddings etc.
iframe.style.height = height + 'px'
var width = content.offsetWidth + 15
iframe.style.width = width + 'px'
But inspect the size of your 'content' element you adapt to, because often the element is much greater than the visible content.
Upvotes: 0