Keeping the Footer at the Bottom of the Page

In this post I'll show you how to keep the footer where it belongs using CSS Grid

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

When creating a website with dyanmic content, we sometimes face a problem where the content on the page doesn't fill the page and the footer, rather than staying in the bottom, moves up leaving blank space beneath it.

There are many ways to solve this problem like,

  • Absolute positioning the footer at the bottom (this doesn't work when content grows larger than the viewport, the footer gets ‘stuck’ to the bottom of the viewport.)

  • Using sticky or fixed positioning (this works if you want your footer to always be visible ;(

  • Using Flexbox or Grid (Both of these technologies allows us to get the behaviour we want but in my opinion using grid is easier and more elegant)

I'll explain how to use grid to push footer at the bottom in this post and let's leave flexbox for a later post.

Page Structure

Your page structure should match the html below.

<body>
   <div class="page-wrapper">
       <header>HEADER</header>
       <main>MAIN</main>
       <footer>FOOTER</footer>
   </div>
</body>

Maybe your page structure is somewhat more complex, in that case you need to keep in mind to put your Header, Footer and Main inside a parent container.

Applying CSS Magic

.page-wrapper {
    min-height: 100vh;
    display: grid;
    grid-template-columns: 100%;
    grid-template-rows: auto 1fr auto;
}

Let see what each line of above code does.

  • min-height: 100vh - Here we are telling the browser to fill the entire viewport
  • display: grid - This line makes the element a grid container
  • grid-template-columns: 1fr - We are creating a single column and giving it a width of 1fr. If that 1fr is new to you, it essentially means “take the remaining space” which, in this case, is the entire width of the grid container, .page-wrapper.

Now the most important line,

  • grid-template-rows: auto 1fr auto:

    • Here we are telling the brower to create three rows. The first and third row, which is the header and footer, respectively, are sized with auto, which means they’ll take up as much space as needed. In other words: no need for hard-coded sizes! (isn't css grid just awesome?)
    • The middle row is our content. We’ve assigned it a size of 1fr which, again, just means it takes up all of the remaining space that’s left over from the other two rows. If you’re wondering why we aren’t making it auto as well, it’s because the entire grid spans the viewport’s whole height, so we need one section to grow and fill up any unused space.

I've prepared a working example on codepen. Go ahead and see what happens when you type more text.

No Comments Yet