why does margin-top auto only work if parent is a flex container

Hey, i made this example for someone and i'm not quite sure the in depth reasoning as to why setting margin-top: auto; on a child (in this case nav) doesn't work unless the parent is a flex container (in this case .site-container), i just know it works and i'd like to understand a little more. I'd appreciate any help, thanks in advance. https://codepen.io/deerCabin/pen/OJeLPYW
2 Replies
Kevin Powell
Kevin Powell5mo ago
margin-top and margin-bottom auto will be calculated as 0 on an element, unless it's a grid or flex item. Goes back to the first version of the CSS spec, where that's the behavior they outlined, probably because of the technical contraints of browsers at the time. With the addition of flex (and later grid), they were able to have auto work in those contexts, because browsers could do it, and since it was a new thing that you have to opt in to, it wouldn't break any old sites. Because auto on the top and bottom resolves to 0, in the old days, it was common to simply do margin: auto, instead of margin: 0 auto;.
snxxwyy
snxxwyyOP5mo ago
Ohh that makes sense, I appreciate the explanation, thank you.
Want results from more Discord servers?
Add your server