loading...
Cover image for Sticky Footer with Flexbox

Sticky Footer with Flexbox

yas46 profile image Yasser Beyer Updated on ・2 min read

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:

  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;
}

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.

Posted on Sep 18 '19 by:

yas46 profile

Yasser Beyer

@yas46

WEB/UI Engineer, JavaScript Programmer, Motorcycle Enthusiast, Builder, Father, and Husband.

Discussion

markdown guide