CSS Flexbox is for one-dimensional layout (arranging items along a single row or column: navigation bars, button groups, centring, cards in a row), while CSS Grid is for two-dimensional layout (rows and columns at the same time: page frames, product grids, dashboards). In real projects you use both: Grid builds the overall page frame, Flexbox arranges the content inside each area. This lesson explains the core properties of each tool, gives a quick decision table, and walks through a product listing page that changes its number of columns on phones, tablets and desktops, with column widths calculated to the pixel.
By the end of this lesson, you will be able to:
- Tell one-dimensional from two-dimensional layout and choose Flexbox or Grid for each part of an interface.
- Use the core Flexbox properties:
justify-content,align-items,flex-wrap,gapandflex. - Use the core Grid properties:
grid-template-columns, thefrunit,repeat(),minmax()andgrid-template-areas. - Build a responsive product listing page and calculate the column count and column width at each screen size.
- Fix four layout mistakes beginners often make, using the browser's Flexbox and Grid inspectors.
Learning frontend web development properly? Flexbox and Grid belong to the step "CSS, Flexbox, Grid and responsive design" in the roadmap. See the 9-step frontend developer roadmap to learn in the right order, from semantic HTML to a portfolio project.
What problems do Flexbox and Grid solve?
Before Flexbox and Grid, developers built layouts with float, HTML tables or negative margin tricks. Centring a box vertically was a classic interview question. These two tools were designed specifically for layout and have long been supported by every modern browser.
One dimension or two
The deciding question is: are you arranging along one axis or two at once? A navigation bar only needs items in a row, spaced out; that is one dimension, so use Flexbox. A product grid needs cards aligned both across rows and down columns; that is two dimensions, so use Grid. Flexbox can wrap (flex-wrap), but each line sizes itself independently, so cards on the next line are not guaranteed to line up with the line above.
Content-first or frame-first
Another way to think about it: with Flexbox, content size drives the layout, and items grow and shrink around their content. With Grid, you draw the frame first (how many columns, how wide), then place content into it. Sketching in pencil as in Figure 1 before writing CSS shows you straight away which parts are frames (Grid) and which are just a row of items (Flexbox).
Photo: Green Chameleon craftedbygc / Wikimedia Commons, CC0
Flexbox: the core properties
Flexbox has a parent (the flex container) and its direct children (flex items). You switch Flexbox on with display: flex on the parent.
Main axis and cross axis
By default flex-direction: row: the main axis is horizontal and children run left to right; the cross axis is vertical. Switch to column and they swap. justify-content aligns along the main axis, align-items along the cross axis. Remember those two sentences and you will stop mixing them up.
.site-header {
display: flex;
justify-content: space-between; /* logo left, menu right */
align-items: center; /* centre vertically */
gap: 16px; /* space between children */
padding: 12px 24px;
}
Growing and shrinking items with flex
The flex property is shorthand for three values: flex-grow (whether the item expands into spare space), flex-shrink (whether it shrinks when space is short) and flex-basis (its starting size). For a search box that takes all remaining space in the header: flex: 1. For a "Log in" button that keeps its size: flex: none.
Wrapping and centring
By default children stay on one line and get squeezed when space runs out. Add flex-wrap: wrap to let them wrap. To centre a box both horizontally and vertically, give the parent display: flex; justify-content: center; align-items: center; and a defined height. Use gap for spacing instead of margin on each child, so you do not have to deal with extra space after the last item.
Grid: the core properties
Grid also has a parent (the grid container) and children (grid items). You switch Grid on with display: grid, then declare columns and rows.
Declaring columns with fr, repeat and minmax
The fr unit means "one share of the remaining free space". grid-template-columns: 240px 1fr creates a fixed 240px left column and a right column that takes the rest. repeat(3, 1fr) creates three equal columns. Most powerful is combining auto-fill with minmax(): the browser fits as many columns as it can, none narrower than the minimum.
.product-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 16px;
}
Naming areas with grid-template-areas
For a page frame, named areas make CSS read like a drawing. Each string is a row and each name is a cell:
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 24px;
}
.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }
Letting one cell span several columns
A large promotional card in a product grid can span two columns with grid-column: span 2. Flexbox cannot do this neatly, because Flexbox has no concept of columns.
Quick decision table: Flexbox or Grid?
The table lists interface parts common on an online shop and the usual choice. These are widespread habits, not hard rules; what matters is that you can explain your choice.
| Component | Use | Why |
|---|---|---|
| Header: logo, menu, buttons | Flexbox | One row, push two groups to opposite ends |
| Button groups, tags, breadcrumbs | Flexbox | One row that may wrap |
| Centring a dialog or icon | Flexbox (or Grid with place-items: center) | Only one element to align |
| Page frame: header, sidebar, content, footer | Grid | Two dimensions, named areas |
| Product grid, photo gallery | Grid | Cards line up across and down |
| Inside a product card (image, name, price, button) | Flexbox column | One column, push the button to the bottom |
| Multi-column forms with labels and inputs | Grid | Labels and inputs line up in columns |
Combining the two
One element can be both a grid item (a child of the product grid) and a flex container (arranging image, name and price inside). This is the most common pattern in real projects. Do not try to use one tool for everything.
What about Bootstrap and Tailwind?
CSS libraries like Bootstrap and Tailwind generate Flexbox and Grid under the hood. Understand the two native tools and you will be fast with any library, and able to fix layouts when they break. Interviewers for junior roles usually ask about Flexbox and Grid directly, not about a library's class names.
Worked example: a responsive product listing page
You are building a category page for an online shoe shop. Requirements: on desktop, a filter column on the left and the product grid on the right; on tablets and phones, filters on top and the grid below. Product cards are at least 160px wide with 16px between them.
Step 1: semantic HTML
<div> page frame, given the .page class
<header> logo + menu + cart
<aside> filters by size, price, colour
<main> list of <article> elements, one per product
<footer> shop information
</div>
The header bar uses Flexbox as shown earlier. The .page frame uses Grid with grid-template-areas. The grid inside main uses repeat(auto-fill, minmax(160px, 1fr)).
Step 2: work out the columns for each screen
With n columns, the minimum width needed is n × 160 + (n − 1) × 16. The browser picks the largest n that fits, then shares out the leftover space. On desktop the page frame is at most 1200px wide, the filter column 240px and the gap 24px, so the product area is 1200 − 240 − 24 = 936px.
- 5 columns need 5 × 160 + 4 × 16 = 800 + 64 = 864px ≤ 936px: they fit.
- 6 columns need 6 × 160 + 5 × 16 = 960 + 80 = 1,040px > 936px: they do not. So you get 5 columns.
- Each card is (936 − 4 × 16) ÷ 5 = 872 ÷ 5 = 174.4px wide.
| Screen | Product area width | Columns | Card width |
|---|---|---|---|
| Desktop (1200px frame) | 1200 − 240 − 24 = 936px | 5 (864 ≤ 936) | (936 − 64) ÷ 5 = 174.4px |
| Tablet 768px, 24px side padding | 768 − 48 = 720px | 4 (688 ≤ 720) | (720 − 48) ÷ 4 = 168px |
| Phone 375px, 16px side padding | 375 − 32 = 343px | 2 (336 ≤ 343) | (343 − 16) ÷ 2 = 163.5px |
Check the tablet: 5 columns need 800 + 64 = 864px > 720px, so 4 columns is right, and 4 × 160 + 3 × 16 = 640 + 48 = 688px ≤ 720px. Check the phone: 3 columns need 480 + 32 = 512px > 343px, so 2 columns. You write no media query for the product grid at all; auto-fill and minmax do it all. Figure 2 shows the same interface on a large tablet, a small tablet and a phone with different column counts.
auto-fill and minmax().Photo: User:tfinc / Wikimedia Commons, CC BY-SA 3.0
Step 3: change the page frame with one media query
Only the .page frame needs to change. Write mobile-first: one column by default, and the filter column only from 1024px up.
.page {
display: grid;
grid-template-columns: 1fr;
grid-template-areas: "header" "sidebar" "main" "footer";
gap: 24px;
max-width: 1200px;
margin: 0 auto;
}
@media (min-width: 1024px) {
.page {
grid-template-columns: 240px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
}
Step 4: inside each product card
Give each article display: flex; flex-direction: column;. Set margin-top: auto on the "Add to cart" button so it always sits at the bottom of the card, whether the product name takes one line or two. That keeps the buttons in a row level with each other.
Common mistakes and how to fix them
Long text breaks a flex card
Sign: a long product name does not wrap and pushes the card out of its space. Cause: by default a flex item will not shrink below the width of its content. Fix: set min-width: 0 on the child, plus overflow-wrap: anywhere if needed.
Using Flexbox for a product grid
Sign: the last row has 2 cards stretched to one and a half times the width of the cards above. Cause: each Flexbox line redistributes its own free space. Fix: switch to Grid with auto-fill and minmax().
Fixed px widths on every column
Sign: a horizontal scroll bar appears on phones. Cause: the fixed widths add up to more than the screen. Fix: use fr, percentages or minmax(), and only fix columns that really need it (like the desktop filter column).
Mixing up justify-content and align-items
Sign: you try to centre vertically and the item moves sideways. Cause: you set flex-direction: column, which made the main axis vertical. Fix: always identify the main axis first. Open the browser's developer tools (DevTools) and turn on the Flexbox and Grid overlays to see the axes, grid lines and gaps.
A note on teamwork: before changing shared CSS (the page frame, colour variables, the grid), tell your teammates and recheck every page that uses it at three screen sizes at least. One line changed in a shared frame can break dozens of pages you never opened.
Practising with others and testing on real devices
A layout is only really done when it works on an actual phone, not just in the browser's device emulator.
Test three sizes
The minimum habit: test at about 375px (phone), 768px (tablet) and 1280px or more (desktop). Open the page on a real phone over your local network or a test deployment, because the address bar, on-screen keyboard and touch targets on a real device differ from the emulator.
Read code with someone else
Reading CSS together with another person (Figure 3) helps you spot the wrong tool, unnecessary fixed widths or confusing class names. When self-studying, swap exercises with a fellow learner or ask a mentor to review.
Photo: Bdecarne / Wikimedia Commons, CC BY-SA 4.0
Preparing for your portfolio project
The category page in the example is part of the online shop project at the end of the roadmap. Keep your code and note why you chose Flexbox or Grid for each block; interviewers often ask exactly that. Figure 4 shows the kind of teamwork you see when people review code together on a laptop.
Photo: WOCinTech Chat from New York City, United States / Wikimedia Commons, CC BY 2.0
Frequently asked questions
Should I learn Flexbox or Grid first?
Learn Flexbox first, because you meet it most (menus, buttons, centring) and it has fewer concepts. Once main and cross axes feel natural, learn Grid for page frames and grids. With daily practice, both usually take 2–3 weeks.
Can Grid replace Flexbox?
Not completely. Grid can do much of what Flexbox does, but for a row of items sized by their content (menus, tags), Flexbox is simpler and more natural. The two complement each other.
Do Flexbox and Grid work in every browser?
Yes, in modern, up-to-date browsers. Some newer features such as subgrid or container queries should be checked against browser support tables before you rely on them for clients with many users on older devices.
Do I need to memorise every property?
No. A solid grip on the roughly 10 properties in this lesson covers most layouts. Look up the rest when you need it; what matters is choosing the right tool.
Practice and self-assessment
- Build a header with Flexbox: logo on the left, menu in the middle, cart button on the right, all vertically centred.
- Build the category page from the example and check the column count at 375px, 768px and 1280px against your calculations.
- Recalculate the column count and card width if
minmax(160px, 1fr)becomesminmax(200px, 1fr)at all three sizes. - Deliberately create the long-text bug that breaks a card, then fix it with
min-width: 0.
Self-assessment criteria
- Pass: the column count in the browser matches your hand calculation at all three sizes.
- Pass: no horizontal scroll bar at 375px, and the "Add to cart" buttons line up in each row.
- Pass: you can explain why each block uses Flexbox or Grid.
- Not yet: using
floator fixed px widths for every column, or testing at only one screen size.
If you are just starting and unsure what to learn in what order, read where to start learning web development: a 2026 beginner roadmap. With layout solid, move on to the next roadmap step: Modern JavaScript and DOM manipulation, where you make this category page filter products by size, price and colour when the user clicks.
Keep learning frontend development: after CSS and responsive design come JavaScript, Git, React with TypeScript, working with APIs and a real deployed online shop project. See the 9-step frontend developer roadmap.

