我想设计一个带有横幅和iframe的网页。我希望iframe可以填充所有剩余的页面高度,并在浏览器调整大小时自动调整大小。是否有可能不编写JavaScript代码,只使用CSS来完成?

我尝试在iframe上设置高度:100%,结果非常接近,但iframe试图填充整个页面高度,包括横幅div元素的30px高度,所以我得到了不必要的垂直滚动条。它并不完美。

我尝试了CSS的margin, padding属性在DIV上成功地占据了网页的整个剩余高度,但这个技巧在iframe上不起作用。

<身体> < div风格= "宽度:100%;高度:30 px;background - color: # cccccc;" > < / div >旗帜 <iframe src="http: //www.google.com.tw" style="width:100%;高度:100%;" > < / iframe > 身体< / >


当前回答

也许这个问题已经有了答案(上面的一些答案是“正确的”方法),但我想我只是补充我的解决方案。

我们的iFrame是在一个div中加载的,因此我需要一些其他的窗口。看到我们的项目已经严重依赖jQuery,我发现这是最优雅的解决方案:

$("iframe").height($("#middle").height());

当然,“#middle”是div的id。你需要做的唯一额外的事情是,每当用户调整窗口大小时,召回这个大小变化。

$(window).resize(function() {
    $("iframe").height($("#middle").height());
});

其他回答

另一种选择是使用vh

<iframe src='/' style="display:block; border:none; height:100vh; width:100%;"></iframe>

另一种方法是使用position: fixed;在父节点上。 如果我没记错的话,位置是固定的;将元素绑定到视口,因此,一旦你给这个节点宽度:100%;及高度:100%;属性,它将横跨整个屏幕。从这一点开始,你可以把<iframe>标签放在它里面,并跨越剩余的空间(包括宽度和高度),简单的宽度:100%;高度:100%;CSS指令。

示例代码


body { margin: 0px; padding: 0px; } /* iframe's parent node */ div#root { position: fixed; width: 100%; height: 100%; } /* iframe itself */ div#root > iframe { display: block; width: 100%; height: 100%; border: none; } <html> <head> <title>iframe Test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <div id="root"> <iframe src="http://stackoverflow.com/"> Your browser does not support inline frames. </iframe> </div> </body> </html>

试试下面的方法:

<iframe name="" src="" width="100%" style="height: 100em"/>

这对我很有效

没错,你所展示的iframe的高度是它的容器(body)的100%。

试试这个:

<body>
  <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
  <div style="width:100%; height:90%; background-color:transparent;">
    <iframe src="http: //www.google.com.tw" style="width:100%; height:100%;">
    </iframe> 
  </div>
</body>

当然,将第二个div的高度更改为您想要的高度。

为什么不这样做(对body padding/margin进行轻微调整)

<script>
  var oF = document.getElementById("iframe1");
  oF.style.height = document.body.clientHeight - oF.offsetTop - 0;
</script>