Layout with Flexbox and Grid
The bakery page needs a navigation bar with the logo on the left and links on the right, and a menu of cards laid out in neat rows. For years, layouts like these took fragile tricks. Modern CSS gives you two tools built for the job, and the only real skill is knowing which one to reach for.
The rule
Flexbox arranges items along one line; grid places them in rows and columns.
Flexbox works in one direction at a time. Set it on the parent:
.site-nav {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}- The main axis runs in the
flex-direction:row(left to right, the default) orcolumn(top to bottom). justify-contentspreads items along the main axis:flex-start,center,space-betweenand so on.align-itemslines them up on the other, cross axis:centerputs a small logo and taller links on one middle line.gapsets the space between items.- On a child,
flex: 1lets it grow to fill leftover space.
Grid works in two directions at once. You define the tracks on the parent and the children fall into the cells:
.menu {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem;
}grid-template-columnsdefines the columns.1frmeans one fraction of the free space, sorepeat(3, 1fr)makes three equal columns.- Rows are created automatically as more cards arrive.
- A child can span tracks:
grid-column: span 2makes a featured card two columns wide.
A handy pattern lets the number of columns adjust by itself:
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));This fits as many columns of at least 220 pixels as the space allows.
The shortcut
Ask "Do I care about lining things up in one direction, or in two?" A bar, a row of buttons, a label next to an icon: one direction, flexbox. A gallery or a page skeleton where columns must line up across rows: two directions, grid. You can nest them freely, such as a grid of cards where each card uses flexbox inside.
The navigation bar
Logo and links sit on one line, pushed to opposite ends: flexbox with
justify-content: space-between.
The usual trap: after switching to flex-direction: column, justify-content now works vertically, because the main axis turned with the direction. Reaching for justify-content: center to centre horizontally will then seem to do nothing.
Drills
Answer fast — trust the rule.
A footer needs three links in one row with equal space between them. Which tool fits most naturally?
In display: flex; flex-direction: column;, what does justify-content: center do?
What does grid-template-columns: 2fr 1fr; create?
The menu is repeat(3, 1fr). How do you make the featured cake card two columns wide?
Remember
- Flexbox arranges items along one line; grid places them in rows and columns.
- One direction: flexbox. Two directions that must line up: grid.
- Trap: in a column flexbox,
justify-contentworks vertically.
