BNetz
BNetz

Reputation: 361

iframe with adaptive height, fitting the "rest" of the page

Although a lot of questions have been posted I did not find the answer, so hopefully someone can help.

I have a website which consists of a header and an iframe below it. The iframe's height changes from page to page, sometimes very long, sometimes very small. The iframe must fit the whole width.

I want the height of the iframe to fit the rest of the page (means: the whole page minus the height of the header). I don't care if the iframe is a bit smaller, I am searching for a pixel-exact solution.

Here is a code-example I have generated so far:

<!doctype html>
<html lang="de">
<head>
    <style>

header { border: 2px solid blue; }
.iframewrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 2px solid green;
}
.iframewrapper {
  padding-top: 40%;
  position: relative;
  height: 100%;
  width: 100%;
  border: 2px solid red;

}
    </style>
</head>
<body>
<header>
    <h1>This is the header.</h1>
    <p>Some text.</p>
</header>
<div class="iframewrapper">
<iframe src="iframetest-big.html" frameborder="0" scrolling="yes" />
</div>    
</body>
</html>

You can look at it here (or in this css-fiddle, but this is not very figurative because I am not able to embed an iframe-file from an external url).

Now with this code the iframe is either too small (if I have a big window or a small padding-top in the wrapper-class) or to big, causing the appearance of a second scrollbar (if I have a small window or a big padding-top in the wrapper-class). I try to illustrate the situation in this image: iframe always has the wrong height What is the right way to accomplish this?

Upvotes: 0

Views: 394

Answers (1)

chojnicki
chojnicki

Reputation: 3623

Flexbox is perfect for that. Just set body to 100vh, set direction to column (so one element under another) and let iframe fill entire flexbox except header space.

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
}


iframe {
  width: 100%;
  flex: 1;
  border: 0;
  min-height: 0; /* just due to very small preview stackoverflow fiddle */
}
<!doctype html>
<html lang="de">
<head>
</head>
<body>
  <header>
    <h1>This is the header.</h1>
    <p>Some text.</p>
  </header>
  <iframe src="https://en.wikipedia.org/wiki/Stack_Overflow" />
</body>
</html>

Upvotes: 1

Related Questions