1

Why is it that when I put margin-top auto on an element of the body, nothing happens, but if I put display flex, the element goes towards the end of the body

Thanks for the reply

body {
  margin: 0;
  background: #000;
  /*display: flex;*/
  min-height: 100vh;
}

.footer {
  background: #eee;
  margin-top: auto;
  width: 100%;
  padding: 2em;
}
<footer class="footer">
  Footer
</footer>
  • You have most likely discovered [the peculiar magic of flexbox and auto margins](https://css-tricks.com/the-peculiar-magic-of-flexbox-and-auto-margins/); the `margin` property behavior slightly differently in a `flexbox` context. – Alexander Nied Jul 21 '21 at 20:22

1 Answers1

3

You have discovered the peculiar magic of flexbox and auto margins; the margin property behavior slightly differently in a flexbox context.

From MDN margin: auto`:

The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

This differs from how MDN describes margin: auto in a flexbox context:

A margin set to auto will absorb all available space in its dimension. This is how centering a block with auto margins works. By setting the left and right margin to auto, both sides of our block try to take up all of the available space and so push the box into the center. ...As soon as there is no space available for the auto margin, the item behaves in the same way as all the other flex items and shrinks to try to fit into space.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45