- Published on
Create a sticky footer with CSS
- Authors
- Name
- John Mwendwa
- Github
- John
1. Using the CSS grid
One of the easiest way to have a footer stick at the bottom without it interfering with the normal flow of the content is by using display : grid for the whole body.
html
1..... 2<body> 3 <header >This is the header</header> 4 <main>Your main content </main> 5 <footer>Footer</footer> 6<body> 7......
CSS
1body{ 2 display: grid; 3 grid-template-rows: auto 1fr auto; 4 min-height: 100vh; 5}
In short what we've done here is, we've created a site with 3 rows. The top row being the header, then the middle row is the main section where all the main content goes and the the last row is the footer.
2. Using flexbox
We can use flexbox to create a sticky footer in one of two ways :
html
1..... 2<body> 3 <header >This is the header</header> 4 <main>Your main content </main> 5 <footer>Footer</footer> 6<body> 7......
Method 1
1body { 2 display : flex; 3 flex-direction : column; 4 min-height : 100vh; 5} 6 7main{ 8 flex-grow : 1; 9}
Here what we are simply doing is, we are setting the whole body content to be a flex container and then allowing the main element to take all the available space (grow) that is left in the middle while pushing the header and footer to the top and bottom respectively.
Method 2
1body { 2 display : flex; 3 flex-direction : column; 4 min-height : 100vh; 5} 6 7footer { 8 margin-top: auto; 9}
This one is just a slight variation of method 1. We are setting the body to a flex container but instead of allowing the main element content to grow and take all the available space, we are forcing the footer to sit at the bottom of the page.
You can use either methods to create a dynamic website where the footer always sticks at the bottom and does not interfere with the main content of your page.
3. Using calc() function
To use this method you should know or set the height of your footer.
1<!--HTML--> 2<body> 3 <div class="content">content</div> 4 <footer class="footer"></footer> 5</body>
1.content { 2 min-height: calc(100vh - 50px); 3} 4.footer { 5 height: 50px; 6}
Warning: If you`re creating dynamic websites, avoid using this approach by all means.
Recommendation
In order to create responsive websites, choose to use the grid method or the flexbox method, either of them will never fail you when creating any UI layout.