I am trying to get my footer stick to the bottom of the website, I haven't seen a good answer for making the footer stick to the bottom, when the page height is less than the viewport height and when the viewport height is less than the page height.
2 Answers
If you want a sticky footer, you can use position: fixed;
. For example;
footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
}

- 393
- 2
- 12
-
I want it to go to the bottom of the page when the page is smaller than the window height, and when it is not to just be added at the bottom of the content. I don't want it fixed. – Yiannis128 Dec 02 '19 at 21:38
-
In this case jcal's answer should do the job. – Cafer Elgin Dec 03 '19 at 12:36
You can achieve a sticky footer using flexbox.
Whereas your main
grows using flex-grow:1
if the content is smaller than the height of the screen.
Whereas these are to important parts of the code snippet:
html,body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
main {
flex-grow: 1;
}
header, footer {
height: 50px;
}
header {
background-color: green;
}
.content {
background-color: grey;
overflow: hidden;
}
footer {
background-color: red;
}
html,body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
main {
flex-grow: 1;
}
<header>header</header>
<main>
<div class="content">
content
</div>
</main>
<footer>footer</footer>
p.s.
This works mainly because of the set min-height
and the setting flex-grow: 1
on the flex-child in the middle of the flex-container.
Assuming you have 3 elements in the flex-container with a set height.
The element with flex-grow: 1
will fill the remaining space to reach the parents height. While the other 2 elements just have their height depending on their content.
So as soon your content reaches a size where the content elements min-height
is reached, there is no space to fill anymore and it will behave normally like an element with height: auto

- 871
- 5
- 14
-
Thank's! it worked wonders! Can you elaborate on why this setup works? – Yiannis128 Dec 04 '19 at 02:50
-
I extended the answer. Unsure, if this satisfies your question. But if you have any specific question just ask. – jcal Dec 04 '19 at 17:24
-