Lesson 3 of 4
Flexbox and Grid: building real layouts
2 min read
Flexbox: one dimension
Use Flexbox to lay items out in a row or a column: navbars, button groups, centring, cards with a footer pinned to the bottom.
.navbar {
display: flex;
justify-content: space-between; /* main axis */
align-items: center; /* cross axis */
gap: 16px;
}
.center { display: flex; justify-content: center; align-items: center; } /* perfect centring */On items:
flex: 1→ grow to fill the remaining space (flex: 1 1 0).flex-shrink: 0→ never shrink (avatars, icons).margin-left: auto→ push an item to the far end.flex-wrap: wrapon the container → items move to the next line when space runs out.
Grid: two dimensions
Use Grid when you control rows and columns together: page layouts, card galleries, dashboards.
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 20px;
}That single rule gives a responsive gallery with no media queries: as many 240px+ columns as fit.
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-areas:
"sidebar header"
"sidebar main";
min-height: 100vh;
}
.sidebar { grid-area: sidebar; }Which to choose?
- Content decides the size (a row of tags, a toolbar) → Flexbox.
- The layout decides the size (columns of a page, a card grid) → Grid.
- They combine happily: a Grid page whose cards use Flexbox inside.
Classic interview layouts to practise
- Centre a div horizontally and vertically (three ways: flex, grid
place-items: center, absolute + transform). - Holy grail: header, footer, sidebar, main.
- Card with image, title, text and a button pinned to the bottom (
display: flex; flex-direction: column;andmargin-top: autoon the button). - A responsive navbar that collapses into a menu on phones.
Check yourself
- What does
flex: 1mean? - Write a responsive card grid with one line of CSS.
- When would you choose Grid over Flexbox?
Sign up free to save your progress.