How to keep the footer in the right place (and maintain the sticky-top behavior of the header)
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?
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.
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:
The layout I’m using in this kind of projects is as simple as the following:
…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="header sticky-top">header</div>
<footer>The well behaved footer!</footer>
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.
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.
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!
Hope this turns out to be useful to someone. Stay safe!