Why does setting margin
to auto
break flexbox's baseline alignment?
I want to align a heading with what I'll call accent text according to the baseline. It works fine using display: flex
and align-items: baseline
on the container.
I also want to remove the margin on the left side of the heading, set the margin on the right side of the heading to a specific value, and leave the margins at the top and bottom of the heading to the default (user-agent stylesheet) value. For example, h1 { margin: auto 1em auto 0; }
This is where it breaks and the item alignment appears to revert to the default of stretch.
Now, developer tools shows me that when I set the top and bottom values of the margin to auto
, it actually ends up with a margin of 0 instead of what I expected. However, when I actually set the top and bottom margins to 0 (e.g.: margin: 0 1em 0 0
), the problem doesn't occur.
I've already seen how to work around this problem by just setting margin-left
and margin-right
individually without using the shorthand property, but I'm hoping to get a better understanding of why this is happening.
header {
background-color: #ffd;
display: flex;
justify-content: flex-start;
align-items: baseline;
margin: 0 1em 0 0;
}
h1 {
margin: auto 1em auto 0;
}
<header>
<h1>Heading</h1>
<div class="accent">Accent Text</div>
</header>