Vertically positioning footer once and for all using flexbox

3 min read

Using CSS to position a footer at the bottom of the page should be such a simple concept, but for many reasons, it can be an extremely tedious task that could take up valuable development time.

In this method, we're going to be using flexbox to achieve our goal, wrapping the footer and other main page elements in a flex container.

Firstly, let's run through the specific components that make up our average webpage:

  • Navigation bar: sticks to the top of the page, likely to never move
  • Footer: rests at the bottom of the page after all of the content in the body has rendered
  • Body: contains all the content between the nav and the footer

Website page structure

In order to achieve our goal, we're going to be grouping all of these elements together in a very large flex container, I'll call it '.content'. We can achieve the same result by setting these styles to the <body> tag as long as your nav, body, & footer are direct children to the body. Don't worry, it will make sense why we're doing this in no time. Below is the HTML & CSS required for our page structure.

<div class="content">
    <nav> Nav </nav>
    <section> Body </section>
    <footer> Footer </footer>
</div>
.content {
  display:flex;
  flex-direction:column;
  min-height:100vh;
}

Once our flex container has been set with a minimum height of the users' viewport height, we can discuss the issue.

A very common issue when it comes to styling a footer occurs when it doesn't stick to the bottom of the page, instead, resting below all of our body content. We're going to be tackling this issue by ensuring the body content grows to consume all of the remaining whitespace on the viewport that the footer would otherwise sit above. This is achieved by setting the below-stated flex property to the body container of all of your content.

section {
    flex-grow:1;
}

That's it! The body content should grow to fill the remaining whitespace that the page footer or nav doesn't take up. This is my favorite solution to ensure the footer sticks to the bottom of the page no matter what the document height is!

The full source code for this blog as well as a working CodePen is below.

<body>
  <div class="content">
    <nav>
      Nav
    </nav>
    <div class="body">
      Body
    </div>
    <footer>
      Footer
    </footer>
  </div>
</body>
body {
  margin:0;
  min-height:100vh;
}
.content {
  display:flex;
  flex-direction:column;
  min-height:100vh;
}
nav {
  background-color:salmon;
  height:100px;
}
.body {
  background:lightpink;
  height:200px;
  flex:1;
}
footer {
  background:hotpink;
  height:150px;
}