Search code examples
htmlcssflexboxsticky-footer

Can flexbox be used to 'sticky' the last footer section by expanding the previous footer section?


Given the basic HTML structure (which I can't change) below, I know I can expand the main content div with this CSS:

html,
body {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
}

#columns {
  flex: 1 0 auto;
}

.footer {
  flex-shrink: 0;
}
<body>
  <header>
    HEADER CONTENT
  </header>
  <div id="columns" class="container">
    MAIN CONTENT
  </div>
  <footer class="footer">
    <div class="container"> </div>
    <div id="footer-content">
      FOOTER CONTENT
   </div>
  </footer>
</body>

But the 'columns' section has styling that I don't really want extending below the content, so I would prefer, if possible, to expand the penultimate empty div (.container) within the footer section.

I've tried everything I can think of, but I'm a css beginner and nothing has worked.

Can this be done?


Solution

  • I figured it out using codepen in SCSS mode so I could nest selectors. That made experimenting a whole lot easier.

    It turned out I needed two flexboxes: one to expand the whole footer section to fill the available space, and one within the footer to expand the padding container likewise.

    Here's the code with background-color added to each content section for illustration purposes:

    html,
    body {
      height: 100%;
    }
    body {
      display: flex;
      flex-direction: column;
      margin: 0;
    }
    body header {
      background-color: green;
    }
    body #columns {
      background-color: blue;
    }
    body #footer-content {
      background-color: red;
    }
    body .footer {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    body .footer .container {
      flex: 1;
    }
    <body>
      <header>
        HEADER CONTENT
      </header>
      <div id="columns" class="container">
        MAIN CONTENT
      </div>
      <footer class="footer">
        <div class="container"> </div>
        <div id="footer-content">
          FOOTER CONTENT
       </div>
      </footer>
    </body>