Fix Footer at Bottom of the Page with CSS (Even with Little Content)

written by idriss douiri profile picture Idriss Douiri

2 min read

footer a the bottom of a page, and text saying: Footer always at the bottom
share

When not all of your pages have enough content, and you want to fix the footer at the bottom, the first solution that might come to your mind is a fixed position. However, this won’t work as you expect, as it will always make your footer visible on the screen, even when you have enough content that could push it to the bottom.

Instead, you should use one of the two methods covered in this article to make your content push your footer to the bottom, even if you don’t have much content.

a table comparing between fixing the footer at the bottom using fixed position vs display grid or flex methods and the limitation of fixed position

Note that in this article, I assume that your html structure is similar to this:

<body>
	<header><!--content--></header>
	<main><!--content--></main>
	<footer><!--content--></footer>
</body>

Make sure to adjust your code based on your structure.

Important CSS Setup

Before we can place each element in its position, the container should fill the height of the entire viewport. In this case, the container is the body so we can give it a min-height of 100vh to allow it to grow as it gets more content but never be smaller than the screen height:

body {
   min-height: 100vh;
   margin: 0;
}

This first method relies on flex display with a column direction to stack the children vertically, then we can set the flex-grow property to 1 on the <main> element to allow it to grow and take all the available space:

body {
  display: flex;
  flex-direction: column;
}
main {
  flex-grow: 1;
}

Like the flex method, we can use the grid layout to achieve the same result with fewer lines of code.

After setting the display property to be grid on the container, we can control how its rows are defined using grid-template-rows with the value auto 1fr auto. This ensures that the <header> and <footer> rows take only the height they need, while the middle row expands to fill the remaining space., causing the footer to stick to the bottom of the screen:

body {
  display: grid;
  grid-template-rows: auto 1fr auto;
}

Conclusion

Either one of these methods will work fine. However, you need to adjust the code based on your structure, or otherwise, it might not work.