A Page footer should be always kept at the bottom of the page, for some it is maybe a difficult task, taking 1-2 hours to accomplish while it is pretty simple. Probably you are reading this right now because you are stuck on it. Letโs show you how to keep the footer where it belongs in 2 steps (with explanation).
TL;DR Go to the bottom to see the code.
1- add a footer under your body then add a class .footer to it, then add these properties to the class.
.footer {
position: absolute;
background-color: #333;
color: white;
width: 100%;
bottom: 0;
}
Explanation :
- putting a position absolute in our footer will remove it from the document flow so we are free to give it a new position.
- Since it is a position absolute we give it a bottom: 0, but this wont let the footer go to the bottom of the page, instead it will be placed relatively to the containing block which is the body in our case.
2- We should now create an HTML element under body wrapping all pages content including footer and header, add to this element a class and letโs call it .mainContainer
.mainContainer {
position: relative;
min-height: 100vh;
}
Magic !, Now the footer is at the bottom of the page.
Explanation :
- When an element with a position:absolute contained by an element with a position: relative it will be placed according to the parent element.
- giving a min-height : 100vh means that the mainContainers height will always take 100% of the browser page height.
As a final result, you have now the footer at the bottom of the page, contained by mainContainer.
TL;DR Here is the code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<div class="mainContainer">
<div>
My content
</div>
<footer class="footer">
My footer
</footer>
</div>
</body>
</html>
in your main.css
.mainContainer {
position: relative;
min-height: 100vh;
}
.footer {
position: absolute;
background-color: #333;
color: white;
width: 100%;
bottom: 0;
}
you can follow me on twitter.
Check my website iLoveSemicolons.io for more articles/tutorials and Open Source project
Happy coding :)
Top comments (0)