#Sticky footer with display: flex
Solution inspired by Philip Walton's sticky footer.
This solution is valid only for:
- Chrome ≥ 21.0
- Firefox ≥ 20.0
- Internet Explorer ≥ 10
- Safari ≥ 6.1
It is based on the flex
display, leveraging the flex-grow
property, which allows an element to grow in either height or width (when the flow-direction
is set to either column
or row
respectively), to occupy the extra space in the container.
We are going to leverage also the vh
unit, where 1vh
is defined as:
1/100th of the height of the viewport
Therefore a height of 100vh
it's a concise way to tell an element to span the full viewport's height.
This is how you would structure your web page:
----------- body -----------
----------------------------
---------- footer ----------
----------------------------
In order to have the footer stick to the bottom of the page, you want the space between the body and the footer to grow as much as it takes to push the footer at the bottom of the page.
Therefore our layout becomes:
----------- body -----------
----------------------------
---------- spacer ----------
<- This element must grow in height
----------------------------
---------- footer ----------
----------------------------
The above described method is implemented as follows
<html>
<body>
<div class="content" />
<div class="spacer" />
<footer class="footer" />
</body>
</html>
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.spacer {
flex: 1;
}
You can have a look at the JSFiddle.
Be aware that Safari has a flawed implementation of the flex-shrink
property, which allows items to shrink more than the minimum height that would be required to display the content.
To fix this issue you will have to set the flex-shrink
property explicitly to 0 to the .content
and the footer
in the above example:
.content { flex-shrink: 0; }
.footer { flex-shrink: 0; }