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.

Open
The hero is as tall as the frame, and its title sits centered between the toolbar and the line at the bottom. In the toolbar the account link is pushed to the far end. Scroll down: the two cards are the same height and both buttons sit on the bottom edge, whatever the length of the text.
Code CSS · 23 lines
.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 3 reasons · 5 rules · support · credits

Why it works

  1. 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.
  2. 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.
  3. gap still applies. It is the least space the pushed item keeps when there is no free space left.

Rules

  1. 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%.
  2. 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.
  3. Write min-block-size, never block-size. A fixed height cuts off long content.
  4. This is a flex technique. In a grid column the spare height goes to the rows first and every child grows.
  5. It replaces a spacer element, space-between on 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.

Credits

Borrowed from: Heydon Pickering and Andy Bell, The Stack, section "Splitting the stack", and The Cover, Every Layout. The Cover gives every child a margin and removes it at both ends. gap does that in one declaration.

Docs: MDN: Aligning items in a flex container