我想设计一个带有横幅和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 > 身体< / >


2019年更新

现在最好的选择是- flexbox。多年来,所有东西都很好地支持它。去吧,不要回头。下面是一个flexbox的代码示例:

正文,HTML{宽度:100%;高度:100%;保证金:0;填充:0} .row-container{显示:flex;宽度:100%;高度:100%;flex-direction:列;背景颜色:蓝色;溢出:隐藏;} .第一行{background-color:石灰;} .第二行{flex-grow: 1;边界:没有;保证金:0;填充:0;} < div class = "行容器”> < div class = "板凳”> < / p > < p >一些文本 <p>和一些更多的文本</p> < / div > <iframe src="https://jsfiddle.net/about" class="second-row"></iframe> < / div >

剩下的答案留给学习和历史原因。


关键是要明白这100%是什么。阅读CSS规范可以帮助你。

To make a long story short - there is such a thing as "containing block" - which is not necessary the parent element. Simply said, it is the first element up the hierarchy that has position:relative or position:absolute. Or the body element itself if there is nothing else. So, when you say "width: 100%", it checks the width of the "containing block" and sets the width of your element to the same size. If there was something else there, then you might get contents of a "containing block" that are larger than itself (thus "overflowing").

身高也有同样的作用。只有一个例外。你不能让高度达到浏览器窗口的100%。最顶层的元素是body(或html?)不确定)元素,并且该元素的延伸足以包含其内容。指定高度:100%对它没有影响,因为它没有“父元素”来测量100%。窗口本身不算数。;)

要让某样东西伸展到窗口的100%,你有两个选择:

使用JavaScript

Don't use DOCTYPE. This is not a good practice, but it puts the browsers in "quirks mode", in which you can do height="100%" on elements and it will stretch them to the window size. Do note, that the rest of your page will probably have to be changed too to accommodate for the DOCTYPE changes. Update: I'm not sure if I wasn't wrong already when I posted this, but this certainly is outdated now. Today you can do this in your stylesheet: html, body { height: 100% } and it will actually stretch to the whole of your viewport. Even with a DOCTYPE. min-height: 100% could also be useful, depending on your situation. And I wouldn't advise anyone to make a quirks-mode document anymore either, because it causes way more headaches than solves them. Every browser has a different quirks-mode, so getting your page to look consistently across browsers becomes two orders of magnitude more difficult. Use a DOCTYPE. Always. Preferably the HTML5 one - <!DOCTYPE html>. It's easy to remember and works like a charm in all browsers, even the 10 years old ones. The only exception is when you have to support something like IE5 or something. If you're there, then you're on your own anyway. Those ancient browsers are nothing like the browsers today, and little advice that is given here will help you with them. On the bright side, if you're there, you probably just have to support ONE kind of browser, which gets rid of the compatibility problems. Good luck! Update 2: Hey, it's been a long time! 6 years later, new options are on the scene. I just had a discussion in the comments below, here are more tricks for you that work in today's browsers. Option 1 - absolute positioning. Nice and clean for when you know the precise height of the first part. body, html {width: 100%; height: 100%; margin: 0; padding: 0} .first-row {position: absolute;top: 0; left: 0; right: 0; height: 100px; background-color: lime;} .second-row {position: absolute; top: 100px; left: 0; right: 0; bottom: 0; background-color: red } .second-row iframe {display: block; width: 100%; height: 100%; border: none;} <div class="first-row"> <p>Some text</p> <p>And some more text</p> </div> <div class="second-row"> <iframe src="https://jsfiddle.net/about"></iframe> </div> Some notes - the second-row container is needed because bottom: 0 and right: 0 doesn't work on iframes for some reason. Something to do with in being a "replaced" element. But width: 100% and height: 100% works just fine. display: block is needed because it's an inline element by default and whitespace starts creating weird overflows otherwise. Option 2 - tables. Works when you don't know the height of the first part. You can use either actual <table> tags or do it the fancy way with display: table. I'll go for the latter because it seems to be in fashion these days. body, html {width: 100%; height: 100%; margin: 0; padding: 0} .row-container {display: table; empty-cells: show; border-collapse: collapse; width: 100%; height: 100%;} .first-row {display: table-row; overflow: auto; background-color: lime;} .second-row {display: table-row; height: 100%; background-color: red; overflow: hidden } .second-row iframe {width: 100%; height: 100%; border: none; margin: 0; padding: 0; display: block;} <div class="row-container"> <div class="first-row"> <p>Some text</p> <p>And some more text</p> </div> <div class="second-row"> <iframe src="https://jsfiddle.net/about"></iframe> </div> </div> Some notes - the overflow: auto makes sure that the row always includes all of its contents. Otherwise floating elements can sometimes overflow. The height: 100% on the second row makes sure it expands as much as it can squeezing the first row as small as it gets. Recommended: Option 3 - flexbox - The cleanest one of them all. body, html {width: 100%; height: 100%; margin: 0; padding: 0} .row-container {display: flex; width: 100%; height: 100%; flex-direction: column; background-color: blue; overflow: hidden;} .first-row {background-color: lime; } .second-row { flex-grow: 1; border: none; margin: 0; padding: 0; } <div class="row-container"> <div class="first-row"> <p>Some text</p> <p>And some more text</p> </div> <iframe src="https://jsfiddle.net/about" class="second-row"></iframe> </div> Some notes - the overflow: hidden is because the iframe still generates some sort of overflow even with display: block in this case. It isn't visible in the fullscreen view or the snippet editor, but the small preview window gets an extra scrollbar. No idea what that is, iframes are weird.


没错,你所展示的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的高度更改为您想要的高度。


我认为你有一个概念上的问题。要说“我尝试在iframe上设置高度:100%,结果非常接近,但iframe试图填充整个页面”,好吧,什么时候“100%”不等于“整个”?

你已经要求iframe填充它的容器(也就是body)的整个高度,但不幸的是,它在<div>上面有一个块级别的兄弟,你要求它的大小为30px。所以父容器的总大小现在被要求为100% + 30px > 100%!因此滚动条。

我认为你的意思是你想让iframe像帧和表单元一样消耗剩下的东西,即height="*"。IIRC,这个不存在。

不幸的是,据我所知,也没有办法有效地混合/计算/减去绝对和相对单位,所以我认为你只有两个选择:

绝对定位你的div 会把它从容器里拿出来吗 单独的iframe将消耗它的 容器的高度。这就剩下你 还有各种各样的问题 虽然,但也许是为了你 做不透明或对齐将 好的。 或者,您需要指定 %高度的div和减少 iframe的高度减去那么多。 如果绝对高度是 这很重要,你需要申请 这是div的子元素 代替。


您可以通过在加载/调整大小事件上测量正文大小并将高度设置为(full height - banner height)来实现这一点。

请注意,目前在IE8 Beta2中,您不能执行此onresize操作,因为该事件目前在IE8 Beta2中已中断。


我们使用JavaScript来解决这个问题;这是来源。


var buffer = 20; //scroll bar buffer
var iframe = document.getElementById('ifm');

function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}

function resizeIframe() {
    var height = document.documentElement.clientHeight;
    height -= pageY(document.getElementById('ifm'))+ buffer ;
    height = (height < 0) ? 0 : height;
    document.getElementById('ifm').style.height = height + 'px';
}

// .onload doesn't work with IE8 and older.
if (iframe.attachEvent) {
    iframe.attachEvent("onload", resizeIframe);
} else {
    iframe.onload=resizeIframe;
}

window.onresize = resizeIframe;

备注:ifm为iframe ID

pageY()由John Resig (jQuery的作者)创建


或者你也可以使用老派的框架集:

<frameset rows="30,*">
  <frame src="banner.swf"/>
  <frame src="inner.html" />
</frameset>

你可以使用DOCTYPE,但你必须使用table。看看这个:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
*{margin:0;padding:0}
html, body {height:100%;width:100%;overflow:hidden}
table {height:100%;width:100%;table-layout:static;border-collapse:collapse}
iframe {height:100%;width:100%}

.header {border-bottom:1px solid #000}
.content {height:100%}
</style>
</head>
<body>
<table>
    <tr><td class="header"><div><h1>Header</h1></div></td></tr>
    <tr><td class="content">
        <iframe src="http://google.com/" frameborder="0"></iframe></td></tr>
</table>
</body>
</html>

另一种方法是使用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是在一个div中加载的,因此我需要一些其他的窗口。看到我们的项目已经严重依赖jQuery,我发现这是最优雅的解决方案:

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

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

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

在尝试了一段时间的css路由后,我最终用jQuery写了一些相当基本的东西,为我做了这项工作:

function iframeHeight() {
    var newHeight = $j(window).height();
    var buffer = 180;     // space required for any other elements on the page 
    var newIframeHeight = newHeight - buffer;
    $j('iframe').css('height',newIframeHeight);    //this will aply to all iframes on the page, so you may want to make your jquery selector more specific.
}

// When DOM ready
$(function() {
    window.onresize = iframeHeight;
}

在IE8, Chrome, Firefox 3.6测试


MichAdel代码为我工作,但我做了一些小的修改,以使其正常工作。

function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}
var buffer = 10; //scroll bar buffer
function resizeIframe() {
    var height = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
    height -= pageY(document.getElementById('ifm'))+ buffer ;
    height = (height < 0) ? 0 : height;
    document.getElementById('ifm').style.height = height + 'px';
}
window.onresize = resizeIframe;
window.onload = resizeIframe;

我是这么做的。我也遇到了同样的问题,最后花了几个小时在网上搜索资源。

<style type="text/css">
   html, body, div, iframe { margin:0; padding:0; height:100%; }
   iframe { position:fixed; display:block; width:100%; border:none; }
</style>

我把这个添加到头部部分。

请注意,我的iframe位于一个有3行1列的表的中间单元格内。


你可以用html/css这样做:

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

试试下面的方法:

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

这对我很有效


虽然我同意JS似乎是一个更好的选择,我有一个有点CSS只工作的解决方案。它的缺点是,如果您必须频繁地向iframe html文档添加内容,您将不得不调整一个百分比的时间。

解决方案:

试着不要为你的html文档指定任何高度,

html, body, section, main-div {}

然后只编写如下代码:

#main-div {height:100%;}
#iframe {height:300%;}

注意:div应该是你的主要部分。

这应该是相对有效的。iframe精确地计算可见窗口高度的300%。如果第二个文档的html内容(在iframe中)的高度小于浏览器高度的3倍,它就可以工作。如果你不需要频繁地向文档添加内容,这是一个永久的解决方案,你可以根据你的内容高度找到你自己需要的百分比。

这是因为它可以防止第二个html文档(一个嵌入)从父html文档继承它的高度。它阻止了它,因为我们没有为它们都指定高度。当我们给子对象一个%时,它会寻找它的父对象,如果没有,它会取它的内容高度。前提是其他容器没有给定高度。


“无缝”属性是一个新的标准,旨在解决这个问题:

http://www.w3schools.com/tags/att_iframe_seamless.asp

当分配此属性时,它将删除边框和滚动条,并将iframe大小设置为其内容大小。 不过它只支持Chrome和最新的Safari浏览器

更多信息请点击这里: HTML5 iFrame无缝属性


一个简单的jQuery解决方案

在iframed页面内的脚本中使用此选项

$(function(){

    if(window != top){
        var autoIframeHeight = function(){
            var url = location.href;
            $(top.jQuery.find('iframe[src="'+ url +'"]')).css('height', $('body').height()+4);
        }
        $(window).on('resize',autoIframeHeight);
        autoIframeHeight();
    }

}

你不能设置iframe高度为%,因为你的父体高度不是100%,所以让父体高度为100%,然后应用iframe高度为100%

For eg.
<html>
<head>
<style>
html,body{height:100%}
</style> 
</head>
<body>
<iframe src="http://www.quasarinfosystem.com" height="100%" width="100%" ></iframe>
</body>
</html>

HTML5新功能:使用calc(对高度)

<html style="width:100%; height:100%; margin: 0px; padding: 0px;">
<body style="width:100%; height:100%; margin: 0px; padding: 0px;">
<div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
<iframe src="http://www.google.com.tw" style="width:100%; height: calc(100% - 30px);"></iframe>
</body>
</html>

以下是一些现代的方法:


Approach 1 - Combination of viewport relative units / calc(). The expression calc(100vh - 30px) represents the remaining height. Where 100vh is the height of the browser and the usage of calc() effectively displaces the height of the other element. Example Here body { margin: 0; } .banner { background: #f00; height: 30px; } iframe { display: block; background: #000; border: none; height: calc(100vh - 30px); width: 100%; } <div class="banner"></div> <iframe></iframe> Support for calc() here; support for viewport relative units here.


Approach 2 - Flexbox approach Example Here Set the display of the common parent element to flex, along with flex-direction: column (assuming you want the elements to stack on top of each other). Then set flex-grow: 1 on the child iframe element in order for it to fill the remaining space. body { margin: 0; } .parent { display: flex; flex-direction: column; min-height: 100vh; } .parent .banner { background: #f00; width: 100%; height: 30px; } .parent iframe { background: #000; border: none; flex-grow: 1; } <div class="parent"> <div class="banner"></div> <iframe></iframe> </div> Since this approach has less support1, I'd suggest going with the aforementioned approach.

1虽然它似乎在Chrome/FF中工作,但它在IE中不起作用(第一种方法在所有当前的浏览器中都有效)。


它将与下面提到的代码一起工作

<iframe src="http: //www.google.com.tw"style="position: absolute; height: 100%; border: none"></iframe>

如果你可以访问将要加载的iframe的内容,你可以告诉它的父元素在它调整大小的时候调整大小。

    $(window).resize(function() {
        $(parent.document)
            .find("iframe")
            .css("height", $("body").css("height"));        
    }).trigger("resize");

如果页面上有多个iframe,您可能需要使用id或其他聪明的方法来增强.find(“iframe”),以便选择正确的iframe。


类似的答案@MichAdel,但我使用JQuery和更优雅。

<script type="text/javascript">
    $(document).ready(function() {
        var $iframe = $('#iframe_id')[0];

        // Calculate the total offset top of given jquery element
        function totalOffsetTop($elem) {
            return $elem.offsetTop + ($elem.offsetParent ? totalOffsetTop($elem.offsetParent) : 0);
        }

        function resizeIframe() {
            var height = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
            height -= totalOffsetTop($iframe);
            $iframe.height = Math.max(0, height) + 'px';
        }

        $iframe.onload = resizeIframe();
        window.onresize = resizeIframe;
    });
</script>

iframe_id为iframe标签的ID


我认为最好的方法来实现这个场景使用css位置。设置位置相对于你的父div和position:绝对于你的iframe。

.container { 宽度:100%; 位置:相对; 身高:500 px; } iframe { 位置:绝对的; 宽度:100%; 高度:100%; } < div class = "容器" > < iframe的src = " http://www.w3schools.com " > <p>你的浏览器不支持iframes < / iframe > < / div >

for other padding and margin issue now a days css3 calc() is very advanced and mostly compatible to all browser as well.

检查calc ()


我使用display:table来修复类似的问题。它几乎适用于此,留下一个小的垂直滚动条。如果您试图用iframe以外的东西填充这个灵活的列,它可以工作(不是

使用下面的HTML

<body>
  <div class="outer">
    <div class="banner">Banner</div>
    <div class="iframe-container">
      <iframe src="http: //www.google.com.tw" style="width:100%; height:100%;border:0;"></iframe>
    </div>
  </div>
</body>

更改外部div以使用display:table,并确保它具有宽度和高度设置。

.outer {
  display: table;
  height: 100%;
  width: 100%;
}

将横幅设置为一个表格行,并设置它的高度为您的偏好:

.banner {
  display: table-row;
  height: 30px;
  background: #eee;
}

在你的iframe(或任何你需要的内容)周围添加一个额外的div,并使它成为一个高度设置为100%的表行(设置它的高度是至关重要的,如果你想嵌入一个iframe来填充高度)

.iframe-container {
  display: table-row;
  height: 100%;
}

下面是一个jsfiddle显示它在工作(没有iframe,因为这似乎不工作在小提琴)

https://jsfiddle.net/yufceynk/1/


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

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

另一种选择是使用vh

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