The purpose of a sticky footer is that it “sticks” to the bottom of the browser window. But not always, if there is enough content on the page to push the footer lower, it still does that.
But if the content on the page is short, a sticky footer will still hang to the bottom of the browser window.
In this article, we will explain few ways to stick the footer to the bottom of the page if there is not enough content.
Sticky Footer Using Flexbox
Using Flexbox in CSS we can fix it very easily with following steps.
- First set the
min-height
of body to100vh
. - Set the body
display
toflex
andflex-direction
tocolumn
. - Select footer element and set
top margin
toauto
.
CSS should look something like this.
body { min-height: 100vh; display: flex; flex-direction: column; } footer { margin-top: auto; }
Result
See the Pen Sticky Footer Using Flexbox by Sunil Pradhan (@Sunil_Pradhan) on CodePen.
Sticky Footer Using Grid
The grid method is even more simple compared to flexbox. Here we just need to modify the main layout element. This requires just 3 lines of code.
body { display: grid; grid-template-rows: auto 1fr auto; min-height: 100vh; }
To understand better the above CSS code, we are applying fr
(Fractional unit) for wrapper element to be flexible. We have Header, Wrapper, and Footer, hence grid-template-rows: auto 1fr auto
.
If it’s just two elements like Wrapper and Footer then the grid-template-rows
value will be 1fr auto
.
Result
See the Pen Sticky Footer Using Grid by Sunil Pradhan (@Sunil_Pradhan) on CodePen.
Conclusion
Which method you choose is entirely up to you, and the specifics of your design. Hopefully, the above example help you save some time in making your decision and implementing it.
We personally do not recommend using JavaScript to stick footer at bottom of a page. As we know flexbox and grid are the easier ways.
There are many other ways but more complicated, above two methods are the best from our perspective.
Hope you learnt few things from this article. Thank you.
Add comment