How does margin-top: auto; work?

Hey All,

I was looking for a solution to keep my footer either pinned to the bottom of the page or the content, whichever is greater, and found the following solution. It works, but I can't wrap my head around why
margin-top: auto;
is working the way it is?

When I don't have enough content the margin-top is some calculated value, and when the content is bigger than the page the margin-top is 0.

Here's the basic code:

<html>
  <head></head>
  <body>
    <header></header>
    <main>
      <!-- Content -->
    </main>
    <footer></footer>
  </body>
</html>


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

  footer {
    margin-top: auto;
  }
Was this page helpful?