DEV Community

Cover image for Put Footer at The Bottom with CSS Flexbox
CY
CY

Posted on • Originally published at cyishere.dev

Put Footer at The Bottom with CSS Flexbox

I thought I knew how to use Flexbox to put a footer at the bottom until I read @5t3ph's "ModernCSS 01". I used to wrap <header> and <main> in a div together along with a <footer> then add justify-content: space-between; on the body to make <footer> at the bottom. But Stephanie's solution is using margin-top: auto;! It's extremely inspiring.

To figure out this one trick I learned and discovered more things.

By the way, the cover image is my solution, it's not bad, but it could be better.

  • I've learned from Josh W Comeau's CSS course that flexbox is a completely different layout mode than "the normal one". And margins don't collapse on flexbox.
  • For block level elements (with certain width size), the auto value of margin would take up all available space in the given direction (left/right). This is why we use margin: 0 auto; to center a block element.
  • Because there's no margin collapse on flexbox, when apply an margin-top: auto to an flexbox element, the margin would horizontally take up that available space, just like the vertical effect on block elements. This is why there's a margin-top: auto; trick in Stephanie's solution.

In this pen I put in an article block with margin-left: auto; for compare.

I hope this article could help people know more about CSS flexbox.

Discussion (0)