38

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Nicolas Wilhem
  • 445
  • 1
  • 6
  • 15

1 Answers1

69

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>
Community
  • 1
  • 1
SW4
  • 69,876
  • 20
  • 132
  • 137
  • 2
    Compatibility: http://caniuse.com/#feat=viewport-units (spoiler: not a happy ending.) – Ben Oct 23 '15 at 21:48
  • @Steve - with the exception of Opera8 and – SW4 Nov 02 '15 at 20:50
  • That solution hasn't been working for me. I found this, and it finally works! Don't forget to add "min-width". https://github.com/hakimel/reveal.js/issues/1554 – Leviathan Mar 11 '23 at 12:07