web #css #flexbox

Easy Sticky Footer with Flexbox

Jan 4 '19 · 5 min read · 621

Minimal fuss and dynamic sticky footer using mighty Flexbox. Be gone fixed footer!

Introduction

A

ll web developers will have to tackle sticky footers at some point in their career. It's one of those things that are unavoidable when you come across the need for them. Sticky footers stick to the bottom of the viewport when the content of a web page (more specifically the document) is shorter than the viewport height. When there is more content, the footer sticks to the bottom of the content.

Sticky footer with small amount of content vs more content

Although the sticky footer is such a common problem - historical almost - there is surprisingly no built-in solution. This is usually not a problem, with a catalog of CSS solutions. However, most of these solutions require a fixed height footer. This used to be OK when display sizes were fairly constant, but in the age of mobile-first design - and the plethora of differing screen sizes now out in the digital ecosystem - assuming a fixed footer is no longer an acceptable solution.

You could of course just add a bunch of media queries to keep changing the fixed height of the footer to add the extra flexibility, but with the rise of mighty Flexbox there is a cleaner and more dynamic approach.

Flexible Stickyness

With Flexbox, all you have to do is wrap all the document body - including the footer - in flex container, and the main content - everything except the footer - in another container. This way, you can choose which child elements of the flex container you want to expand using the flex-grow property. For a dynamic sticky footer, this means growing the main content container to automatically take up all the available space in the parent flex container. Note that flex: 1 is short hand for flex: 1 1 0, which sets flex-grow: 1; flex-shrink: 1; flex-basis: 0;.

HTML

<body class="body">
  <header>Some header here</header>
  <main class="main-content">Some main content</main>
  <footer>Some footer</footer>
</body>

CSS

.body {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.main-content {
  flex: 1;
}