DEV Community

Cover image for Sticky Footer with Flexbox
Yasser Beyer
Yasser Beyer

Posted on • Updated on

Sticky Footer with Flexbox

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

To keep a footer stuck to the bottom of the page or the viewable window using Flexbox, you will need to:

  1. Set the footer's parent element's CSS display value to flex and flex-direction value to column.

    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.

  2. 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 to 100%.
body {
  display: flex;
  flex-direction: column;
  height: 100%;
}

main {
  flex: 1 0 auto;
  min-height: auto;
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)