Let’s say you’re creating a landing page for a webinar.
You have an
<h1> heading at the top of the page and a YouTube live stream embedded in an
<iframe> just below it.
When it comes to height, you want the iframe to take up whatever window height is left after the heading. But if you give it a CSS
height property of
100%, the iframe takes up the entire height of the window—and a scroll bar appears.
So how do you solve this?
The Answer Is CSS Inheritance
The answer is in CSS inheritance.
When you give the iframe a CSS
height property of
100%, its height becomes 100% of that of its parent element.
In the case of our example, the parent of the
<iframe> is the
<body> element, whose parent, in turn, is
<html>. Since both the
<html> tags have been assigned the height of the window, 100% of that height also equates to that height.
How to Solve This
Although there are probably other ways to solve this, the two best ways I could think of involved the calc() function when the height property of the heading is fixed, and flexbox when it isn’t.
With the Calc() CSS Function
One way to solve this is to wrap the heading and iframe in
<div> elements, then give the heading wrapper a fixed height and use the
calc() function in CSS to give the iframe wrapper a height of
100vh minus the height of the heading:
You may also want to add a
height: 100% property above the
height: 100vh - 50px property as a fallback for legacy browsers that don’t support the
calc() function from CSS3 and/or height declared in
With the Flexbox CSS Layout
If you can’t assign a fixed height for your heading, then another solution is to set the
display property of the container
flex, then assign a
flex-grow property of
1 to your iframe’s wrapper:
When it comes to the browser compatibility of this solution, the only browser you need to watch out for is Internet Explorer 10 (if supporting it is part of your technical requirements).