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.