Create a Flexbox Sticky Footer in Four Steps

Step 1: Write the HTML

See the Pen Make a Sticky Footer With Flexbox: Step 2 by Float Nine (@floatnine) on CodePen.

This is pretty simple. We have a <header>, <main>, and <footer> tag, with a <textarea> tag in the main section so when we’re done we can see how the page works when we expand it.

Step 2: Add color and dimension

See the Pen Make a Sticky Footer With Flexbox: Step 2 by Float Nine (@floatnine) on CodePen.

We do a couple straightforward things in step 2. First we add a background color to each of the three main elements. Second, we give the header and footer a minimum height so when we apply the flexbox they will stay static (Once display:flex is applied in step 3, min-height can be replaced with flex-basis).

Step 3: Add the flexiness

See the Pen Make a Sticky Footer With Flexbox: Step 3 by Float Nine (@floatnine) on CodePen.

Step 3 is crucial because here we apply display:flex to the body element, which we will see will give the footer its sticky appearance in step 3. We’ve also set the flex-flow to column, because the header, main, and footer sections need to be stacked on top of each other in a single column.

Finally, we’ve added some styling to the textarea element to make things look more like an actual webpage.

Step 4: Add flex-grow to the  main section

Finally, we give the body and html elements a 100% height, and set main to flex-grow:1. Setting main to flex-grow:1 means that the body container (the flexbox) will expand to at least the height of the viewport on load. Giving main a setting of flex-grow:1 means that it will expand to fill the middle section of the container that the fixed height header and footer don’t. In tandem, this will mean that the direct children of the body tag (the header, main, and footer sections) will always fill at least the height of the viewport, and will expand as needed.

See the Pen Make a Sticky Footer With Flexbox: Step 4 by Float Nine (@floatnine) on CodePen.

The way we see if the sticky footer works is to expand the textarea in the main section. Click and drag it around to see the final effect in action.

Leave a Reply

Your email address will not be published. Required fields are marked *