Centering with margin

Why does margin: auto only center horizontally? how is the browser not able to calculate the vertical margins the same way it would for horizontal margins, even when the element being centered and its parent have known heights
2 Replies
Kevin Powell
Kevin Powell•3w ago
Sometimes it works vertically 😅 It's is because this behavior came from the original spec, which says top and bottom margin of auto will resolve to 0. Why they did that, I'm not 100% sure, but they must have had a reason to do with the technical limitations at the time 🙂 They can't change that behavior in the browsers now, because there are people who have sites that will have margin: auto, knowing that it's the same as writing margin: 0 auto, and if the browsers changed how they handle that, it'd potentially break a lot of existing sites. Now, I did say sometimes it works. If you use grid or flex, you can use auto to center vertically as well. Also if you're using fixed or absolute positioning.
sos
sos•3w ago
Interesting history