HTML sections 100% height of viewport

64,457

NB: vh works only for laptops and bigger screen sizes because for mobile screens which are smaller the vh also takes into account the browser window which shows the website and the items such as the volume, battery, etc above the browser window.

This can be done in CSS alone, no Javascript required.

The correct way is to use the vh and vw units:

vh: 1/100th of the height of the viewport.

vw: 1/100th of the width of the viewport.

As such, giving the element you wish to be 100% as high as the viewport a height setting of 100vh will give you what you're after.

html,
body {
  height: 100%;
  margin: 0;
}
section {
  height: 100vh;
}
section:nth-child(1) {
  background: lightblue;
}
section:nth-child(2) {
  background: lightgreen;
}
section:nth-child(3) {
  background: purple;
}
section:nth-child(4) {
  background: red;
}
section:nth-child(5) {
  background: yellow;
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>

Alternatively, you will need to set the dimensions of the element relative to the parent html and body elements, which will need to have a height of 100%:

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
}
section {
  height: 100%;
  width: 100%;
}
section:nth-child(1) {
  background: lightblue;
}
section:nth-child(2) {
  background: lightgreen;
}
section:nth-child(3) {
  background: purple;
}
section:nth-child(4) {
  background: red;
}
section:nth-child(5) {
  background: yellow;
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
Share:
64,457
Nicolas Wilhem
Author by

Nicolas Wilhem

Updated on December 13, 2020

Comments

  • Nicolas Wilhem
    Nicolas Wilhem over 3 years

    I'm trying to build a one page website with sections (5). I'm trying to make each section 100% width and height of the window. So even if window is resized, the section size adapts to it.

    I've heard about JavaScript but I didn't find any good solution. Can somebody help me? Is it possible with media queries?

  • Ben
    Ben over 8 years
    Compatibility: caniuse.com/#feat=viewport-units (spoiler: not a happy ending.)
  • SW4
    SW4 over 8 years
    @Steve - with the exception of Opera8 and <IE9 they're supported, note that the support item highlighted for IE indicate other properties (e.g. vmax) and not vh, vw- so the above is actually pretty compatible