DEV Community

hmintoh
hmintoh

Posted on • Updated on

Setting child container fill parent container's width and height

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>


Enter fullscreen mode Exit fullscreen mode

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;
}


Enter fullscreen mode Exit fullscreen mode

demo-1

We want .wrapper to span the entire viewport, so we set width: 100vw and height: 100vh.



.wrapper {
  background: lightblue;
  width: 100vw;
  height: 100vh;
}


Enter fullscreen mode Exit fullscreen mode

demo-2

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;
}


Enter fullscreen mode Exit fullscreen mode

We start by setting display: flex to .wrapper:

demo-3

We then set flex-direction: column to set the direction of the flexible items:

demo-4

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;
}


Enter fullscreen mode Exit fullscreen mode

Because we didn't specify a flex on navbar and footer, body takes up the entire space in its parent container .main.

demo-5

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;
}


Enter fullscreen mode Exit fullscreen mode

demo-6

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;
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)