There are a few modern techniques, as well as an older technique, that can be used to make any element stretch to fit its parent (or the browser window) 100% vertically (that is, 100% height). For our purposes, let’s assume we have a single <div>
element (which could be any block element) as a direct child of the <body>
.
Old technique (for older browsers)
First, we can use the old technique that works in older browsers:
* {
box-sizing: border-box;
}
html, body {
height: 100%;
}
.height {
background: lightblue;
min-height: 100%;
}
Code language: CSS (css)
Note that one of the keys to the above technique is ensuring that box-sizing: border-box;
is applied so the child element doesn’t overflow the parent. Also, some padding and margin settings could break this. Here’s a demo:
The key is to keep in mind that, while <body>
and <html>
are going to naturally fit the browser window, the child element will be 100% of the height of the <body>
, even if that means it overflows (e.g. depending on the presence of other elements or margin/padding).
Modern technique using vh units
Instead of percentage units, you can use the well-supportedvh
unit of measurement to get the same effect, but with a little less code, assuming the element is a direct child of the <body>
:
* {
box-sizing: border-box;
}
.height {
background: lightblue;
min-height: 100%;
}
Code language: CSS (css)
Again, this is dependent on inner elements and possibly box-sizing: border-box;
, with no need for 100% height on the parent. But note that this will only work if the element is a direct child of the <body>
because the vh
unit represents 1/100th of the browser (viewport) height.
Modern technique using Flexbox
In some cases, the best solution might be to use flexbox, as follows:
html, body {
height: 100%;
}
body {
display: flex;
}
.height {
background: lightblue;
flex-grow: 1;
}
Code language: CSS (css)
As you can see, box-sizing: border-box;
isn’t required. The flex-grow
property makes the child element grow to fit whatever the height of its parent is, without breaking the layout. You should also keep in mind that this makes all child elements of the <body>
flex items, so you’ll have to weigh the pros and cons of using this solution.