Entry 03
Push one item away with an auto margin
Use it when one item in a flex row or column sits apart from the rest, such as the actions at the bottom of a card, the account link at the end of a toolbar, or a title centered in a full-height section between a header and a footer.
Code
.card {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.card > .actions { margin-block-start: auto; }
.toolbar {
display: flex;
gap: 1rem;
}
.toolbar > .account { margin-inline-start: auto; }
.hero {
display: flex;
flex-direction: column;
gap: 1rem;
min-block-size: 100svh;
}
.hero > h1 { margin-block: auto; }Why it works, the rules and the credits
Why it works
- In a flex container an auto margin takes all the free space on its side. One auto margin pushes the item, and everything after it, to the far end.
- Two opposite auto margins split the free space, so the item sits centered between its neighbors. The header stays at the top and the footer at the bottom, and either can be missing.
gapstill applies. It is the least space the pushed item keeps when there is no free space left.
Rules
- The container needs free space. A card has it when a grid row stretches it to match a taller neighbor. A column that is the only child of a taller box needs
block-size: 100%. - The centered item is centered in the space left over, not in the section. A footer with no header pulls the title up by half the footer's height.
- Write
min-block-size, neverblock-size. A fixed height cuts off long content. - This is a flex technique. In a grid column the spare height goes to the rows first and every child grows.
- It replaces a spacer element,
space-betweenon a container with more than two children, and a wrapper around the group that should stay together.
Support
Auto margins work wherever flexbox does. margin-block in Chrome 87, Firefox 66, Safari 14.1. svh in Chrome 108, Firefox 101, Safari 15.4.