Make Iframe to fit 100% of container's remaining height

Darkthread picture Darkthread · Nov 28, 2008 · Viewed 569.7k times · Source

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 to 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 unnecessary vertical scrollbar. It's not perfect.

I tried CSS margin, padding attribute on DIV to occupy the whole remaining height of a web page successfully, but the trick didn't work on iframe.

Answer

Vilx- picture Vilx- · Nov 28, 2008

Update in 2019

TL;DR: Today the best option is the last one in this answer - flexbox. Everything supports it nicely and has for years. Go for that and don't look back. The rest of this answer is left for historical reasons.


The trick is to understand what the 100% is taken of. Reading CSS specs can help you there.

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").

Height works the same way. With one exception. You can't get height to 100% of the browser window. The very top level element, against which 100% can be calculated, is the body (or html? not sure) element, and that stretches just enough to contain its contents. Specifying height:100% on it will have no effect, because it has no "parent element" against which to measure 100%. Window itself doesn't count. ;)

To make something stretch exactly 100% of the window, you have two choices:

  1. Use JavaScript
  2. 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.