How to keep the footer in the right place (and maintain the sticky-top behavior of the header)

Pedro Magalhaes
3 min readMar 17, 2021

Something that has been bothering me for some time was a way to keep the footer in his rightful place, always on the bottom of the page or beyond if the content is wider, but maintaining the sticky-top behavior of the header.

And what is that sticky-top behavior of the header?

Sticky-top header

Well, to me, particularly in the mobile version of a design, if the content is very wide, the header should only be visible until certain point, beyond which it should be hided.

The ‘right’ behavior for a header

If, like me, you’re using Bootstrap to speed up your progress, this behavior is very simple to achieve. Just add the class ‘sticky-top’ to the element you want to… stick to the top.

However, in order to achieve the disappear effect, the sticky element needs to be inside a parent that as the following CSS rules:

position: absolute;
height: 100%;

https://codepen.io/PMaga/pen/GRNaQzK

General layout

The layout I’m using in this kind of projects is as simple as the following:

General layout

…and I want the header to be fixed at the top, but simultaneously be able to disappear when the scroll is very long.
The footer should be always at the very bottom of the content but, also, when the content is very short, it should rest at the bottom of the page and not at the middle of the design.

So, that’s just a container and inside, a header, a content div and finally the pretended footer.

Finally, the well behaved footer

Going to cerne of the question our HTML skeleton should the following:

div class="body-wrapper">
<div class="header sticky-top">header</div>
<div class="content">Content</div>
<footer>The well behaved footer!</footer>
</div>

Our body wrapper will be, as mentioned before, absolute positioned with 100% height.
The trick, in order to achieve the pretended result for our footer, is to turn our wrapper into a flexbox.

Our flexbox should align its children in columns and its content justify needs to be flex-start. This will allow all the content to be packed toward the start of the flex container.

.body-wrapper {
position: absolute;
height: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
}

To the content div we will need to give the flex-grow: 1. This will allow the element to grow to the necessary size, pushing the next element, our footer, to the bottom of the page content.

.content {
flex-grow: 1;
}

Even if our content is shorter than the viewport size, since our wrapper has 100% height, the footer will rest at the bottom of the page, as we intended it to be.

And that’s it… We now have a well behaved footer!

https://codepen.io/PMaga/pen/abBrGVZ

Hope this turns out to be useful to someone. Stay safe!

--

--