Flexbox is a method of positioning elements in horizontal or vertical stacks and in my experience, the best method to keep a footer at the bottom of a page.
<body>
<nav></nav>
<main></main>
<footer></footer>
</body>
To keep a footer stuck to the bottom of the page or the viewable window using Flexbox, you will need to:
-
Set the footer's parent element's CSS
display
value toflex
andflex-direction
value tocolumn
.
body { display: flex; flex-direction: column; }
display: flex;
makes the<body>
element a flexible box layout module and enables a flex context for all its direct children.flex-direction: column;
stacks all the children elements in a vertical top-to-bottom position. -
Set the footer's sibling expandable element's CSS
flex
value to:-
1
- to stick the footer to the bottom of the viewable screen -
1 0 auto
- to stick the footer to the bottom of the page
main { flex: 1 0 auto; }
flex: 1;
defines the ability of the element to grow if necessary. If there is available space inside the flex container, the item should take it up. This then pushes the<footer>
down and stuck to the bottom. -
Common Gotchas:
- Main content element does not expand to occupy all available space.
- applying
min-height: auto;
to the<main>
element will fix this. - Also, make sure that the body element's
height
is set to100%
.
- applying
body {
display: flex;
flex-direction: column;
height: 100%;
}
main {
flex: 1 0 auto;
min-height: auto;
}
If you are new to flexbox and would like to learn more and understand how it works, this comprehensive guide to CSS flexbox layout explains everything about the method.
Top comments (0)