CSS Layout: Flexbox & Grid
Arrange elements like a professional — center, space and align with Flexbox, and build multi-column layouts with CSS Grid. The two tools behind every modern web layout.
1. The problem layout solves
By default, block elements stack vertically — one on top of the next. Real interfaces need rows, columns, grids, sidebars, centered content. For years this was painful (floats, hacks). Today we have two purpose-built tools: Flexbox for one-dimensional layout (a row or a column), and Grid for two-dimensional layout (rows and columns at once).
2. Flexbox — align along one axis
Turn any element into a flex container, and its direct children become flex items you can align and distribute:
.row {
display: flex;
justify-content: space-between; /* spacing along the main axis */
align-items: center; /* alignment along the cross axis */
gap: 1rem; /* space between items */
}
The two properties you’ll reach for constantly:
justify-content— distributes items along the main axis:flex-start,center,space-between,space-around,flex-end.align-items— aligns items on the cross axis:stretch(default),center,flex-start,flex-end.
The famous “how do I center a div?” answer:
.parent { display: flex; justify-content: center; align-items: center; }
3. Grid — rows and columns together
When you need a true grid (cards in a gallery, a dashboard), use Grid:
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr); /* three equal columns */
gap: 1rem;
}
1fr means “one fraction of the free space”. repeat(3, 1fr) is three equal columns that shrink and grow with the container. Change 3 to 4 and you instantly have four columns — no other changes needed.
Rule of thumb: reach for Flexbox when you’re laying things out in a single direction (a navbar, a button row). Reach for Grid when you have a real two-dimensional structure (a card gallery, a page layout).
4. Build both layouts
Make the nav bar space itself out with Flexbox, and the cards sit in a 3-column Grid.
Your tasks
- ○.row uses display: flex
- ○.row uses justify-content: space-between
- ○.row has a gap between items
- ○.grid uses display: grid
- ○.grid has exactly 3 columns
- ○.grid has a gap between tiles
5. What you learned
You now command the two layout systems that power essentially every website built today. Flexbox for one axis — navbars, toolbars, centering. Grid for two axes — galleries, dashboards, full-page layouts. Change one number (repeat(3, 1fr) → repeat(4, 1fr)) and the whole layout reflows.
Next, we make it work on every screen size: responsive design.
🧪 Want to practise this on your own computer? See how to set up your lab →