Sticky footer with CSS flexbox (Supports variable height)

May 24, 2020

Making the footer of my websites has been a little inconsistent. Every time I needed to do it, I did it in a different way and it usually took a lot of trial and error and error to figure out. This time, I finally found a way that looks very clean and also supports variable height footers. The code is pretty self-explanatory.

One thing worth noting is the flex: 1 in the CSS.

It is equivalent to

flex-grow : 1;    ➜ The div will grow in same proportion as the window-size       
flex-shrink : 1;  ➜ The div will shrink in same proportion as the window-size 
flex-basis : 0;   ➜ The div does not have a starting value as such and will 
                     take up screen as per the screen size available for
                     e.g:- if 3 divs are in the wrapper then each div will take 33%.

HTML

<div id="wrapper">
  <div class="header">Title</div>
  <div class="container">Body</div>
  <div class="footer">
    I'm<br/>
    footer<br/>
  </div>
</div>

CSS

html, body {
  height: 100%;
  margin: 0; padding: 0;  /* avoid scrollbars */
}

.wrapper {
  display: flex;  /* use the flex model */
  min-height: 100%; /* For when the main content doesn't fill the entire page*/
  flex-direction: column;  /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}

.header {
  background: yellow;
}

.container {
  flex: 1;
  border: 1px solid red;
}

.footer{
  background: lime;
}

Subscribe to my email list

© 2024 ALL RIGHTS RESERVED