Making a footer stick to the bottom with CSS

β€” 4 minute read

permalink

Did you Ever want to have a footer that's stuck to the bottom, but will push down if the content is bigger?

For demonstration I've created this image.

CSS sticky footer

What this illustrates is the following:

  • left: Green box is the viewport, yellow is the content which is very small, and the pink footer is stuck to the bottom
  • right: Content is larger than the viewport so it pushed the footer down as well.

For this specific problem, there are quite a few solutions, which all have their pros and cons.

I'll just be demonstrating two of them since I think they are the most mainstream solutions.

The examples will be:

With Flexbox, we can easily make a sticky footer by expanding our content section.

What this means is that we set our body to be a flex element, and the content part will have the flex: 1 0 auto value.

This value forces the content to expand as the biggest element, so if we have a small content area it will auto expand to fill the space.

For the HTML structure we will be using this:

<div class="content">Content goes here</div>
<footer>I'm a sticky footer</footer>

Now let's first add a flex property to our body:

body {
display: flex;
flex-direction: column;
min-height: 100vh;
}

This tells our body element to become a flex element, which flexes elements vertically. Then we make the minimum height based on the viewport.

Then all we have to do is add the following property to our content div.

.content {
flex: 1 0 auto;
}

That line will force the content block to space out between the content and the footer.

See this code action in this Codepen permalink

You can use the button to toggle between no text and a lot of text.

See the Pen CSS flexbox sticky footer by Chris Bongers (@rebelchris) on CodePen.

Now with CSS Grid we can stick a footer to the bottom with a similar setup. We use the same HTML for this method.

<div class="content">Content goes here</div>
<footer>I'm a sticky footer</footer>

Next, for our body tag we use the following styles:

body {
display: grid;
grid-template-rows: 1fr auto;
min-height: 100vh;
}

This will tell our body tag to behave like a grid and have a 2-row layout where the first row will use 1fr which means 1 fraction unit.

It comes down to the first row expanding to whatever it needs or can fill. The footer being set to auto will refrain to the size of the text in the footer.

Then we don't even need any styling for our content div.

See this code example in the following Codepen permalink

Again you can click the button to toggle the copy.

See the Pen CSS grid sticky footer by Chris Bongers (@rebelchris) on CodePen.

So these were two code examples to stick a footer to the bottom with CSS.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter