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?
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>