Centring a box: the one everyone googles
"How do I centre a div" is the oldest joke in CSS, and it was a fair question.
The two tools everyone reaches for first each do half the job.
text-align: center only moves inline content - text, links, images -
inside a box. Put it on the container and the words inside the card shuffle
over; the card itself does not move. margin: 0 auto does move the box, but
only sideways: an auto left or right margin splits the leftover horizontal
space, while an auto top or bottom margin in normal flow just resolves to zero.
There was no vertical equivalent, so people stacked hacks - absolute
positioning plus negative margins, a table cell, a ghost element - because the
language had no way to say "put this in the middle".
Flexbox says it in two properties. Make the parent a flex container and it
gains a main axis and a cross axis:
justify-content places children along the main axis
align-items places them across the cross axis
By default the main axis runs left to right, so justify-content: center is
your horizontal control and align-items: center is your vertical one. Add
flex-direction: column and the axes rotate with it: now justify-content
centres vertically and align-items centres horizontally. Neither property
changed meaning - the axes turned underneath them. That swap is why centring
feels random to anyone who memorised the row case as "justify means across".
Your task: the hero band is 320px tall and the sign-up card is stuck in its
top-left corner. Make .hero place the card dead centre, across and down. The
rules go on the parent, not the card.
You'll practice:
- Making a parent a flex container so it can place its children
- Picking between justify-content and align-items by naming the axis you mean
Related reading: Flexbox: One-Dimensional Layout →