Suppose you want have a template with a navbar
, body
and footer
sections. Our goal is to have the body
container take up the entire space between navbar
and footer
.
<div id="root">
<div class="wrapper">
<nav>navbar</nav>
<main>body</main>
<footer>footer</footer>
</div>
</div>
We start by specifying width: 100%
and height: 100%
in #root
. For demonstration purposes I've some background colors for navbar
, body
and footer
.
#root {
width: 100%;
height: 100%;
}
nav {
background: pink;
}
footer {
background: green;
}
main {
background: yellow;
}
.wrapper {
background: lightblue;
}
We want .wrapper
to span the entire viewport, so we set width: 100vw
and height: 100vh
.
.wrapper {
background: lightblue;
width: 100vw;
height: 100vh;
}
To get the body
container to take up the remaining space in blue, we use flexbox.
.wrapper {
background: lightblue;
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
}
We start by setting display: flex
to .wrapper
:
We then set flex-direction: column
to set the direction of the flexible items:
Next, we specify how much of the remaining space in .wrapper
should be assigned to the body
container. We do this with flex: 1
:
main {
background: yellow;
flex: 1;
}
Because we didn't specify a flex on navbar
and footer
, body
takes up the entire space in its parent container .main
.
However, if we specify a flex property in navbar
and body
, they will take up 1 part and 2 parts of the remaining parent container respectively:
nav {
background: pink;
flex: 1;
}
main {
background: yellow;
flex: 2;
}
And there you have it! β‘
#root {
width: 100%;
height: 100%;
}
nav {
background: pink;
flex: 1;
}
footer {
background: green;
}
main {
background: yellow;
}
.wrapper {
background: lightblue;
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
}
Top comments (0)