Search code examples
htmlcssfooter

Clean way to make footer stick to the bottom of the page?


I am trying to get my footer stick to the bottom of the website, I haven't seen a good answer for making the footer stick to the bottom, when the page height is less than the viewport height and when the viewport height is less than the page height.


Solution

  • You can achieve a sticky footer using flexbox. Whereas your main grows using flex-grow:1 if the content is smaller than the height of the screen.

    Whereas these are to important parts of the code snippet:

    html,body {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    
    main {
      flex-grow: 1;
    }
    
    

    header, footer {
      height: 50px;
    }
    
    header {
      background-color: green;
    }
    
    .content {
      background-color: grey;
      overflow: hidden;
    }
    
    footer {
      background-color: red;
    }
    
    html,body {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    
    main {
      flex-grow: 1;
    }
    <header>header</header>
    <main>
      <div class="content">
        content
      </div>
    </main>
    <footer>footer</footer>

    p.s. This works mainly because of the set min-height and the setting flex-grow: 1 on the flex-child in the middle of the flex-container.

    Assuming you have 3 elements in the flex-container with a set height. The element with flex-grow: 1 will fill the remaining space to reach the parents height. While the other 2 elements just have their height depending on their content.

    So as soon your content reaches a size where the content elements min-height is reached, there is no space to fill anymore and it will behave normally like an element with height: auto