Make Iframe to fit 100% of container's remaini

2019-01-03 07:26发布

I want to design a web page with a banner and an iframe. I hope the iframe can fill all the remaining page height and be resized automatically as the browser is resizing. Is it possible to get it done without writing Javascript code, only with CSS?

I tried set height:100% on iframe, the result is quite close but the iframe tried to fill the whole page height, including the 30px height of banner div element, so I got unneccessary vertical scrollbar. It's not perfect.

Update Notes: Excuse me for not describing the question well, I tried CSS margin, padding attribute on DIV to occupy the whole remining height of a web page successfully, but the trick didn't work on iframe.

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

Any idea is appreciated.

标签: html css iframe
26条回答
贼婆χ
2楼-- · 2019-01-03 08:25

I think you have a conceptual problem here. To say "I tried set height:100% on iframe, the result is quite close but the iframe tried to fill the whole page", well, when has "100%" not been equal to "whole"?

You have asked the iframe to fill the entire height of its container (which is the body) but unfortunately it has a block level sibling in the <div> above which you've asked to be 30px big. So the parent container total is now being asked to size to 100% + 30px > 100%! Hence scrollbars.

What I think you mean is that you would like the iframe to consume what's left like frames and table cells can, i.e. height="*". IIRC this doesn't exist.

Unfortunately to the best of my knowledge there is no way to effectively mix/calculate/subtract absolute and relative units either, so I think you're reduced to two options:

  1. Absolutely position your div, which will take it out of the container so the iframe alone will consume it's containers height. This leaves you with all manner of other problems though, but perhaps for what you're doing opacity or alignment would be ok.

  2. Alternatively you need to specify a % height for the div and reduce the height of the iframe by that much. If the absolute height is really that important you'll need to apply that to a child element of the div instead.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 08:25

A simple jQuery solution

Use this in a script inside the iframed page

$(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();
    }

}
查看更多
登录 后发表回答