DEV Community

loading...
Cover image for Keep the footer at the bottom

Keep the footer at the bottom

ilovesemicolons profile image Sirage Al dbiyat ・2 min read

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
    height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

in your main.css

.mainContainer {
    position: relative;
    height: 100vh;
}

.footer {
    position: absolute;
    background-color: #333;
    color: white;
    width: 100%;
    bottom: 0;
}

Enter fullscreen mode Exit fullscreen mode

Happy coding :)

Discussion (0)

pic
Editor guide