Responsive Flexbox
By the end of this lesson you will be able to make any Flexbox layout respond to screen size in two ways: by changing properties at a breakpoint, and by letting flex-wrap and flex-basis decide for themselves. You will also tune gaps, weigh the real cost of order, and build a holy-grail page that stacks on phones.
You should know Flexbox Basics, Flex Wrap, Flex Grow, Shrink & Basis, Flex Order & Alignment and Media Queries. We will not repeat them; we will combine them.
Two ways to make Flexbox respond
Think of a school assembly. In the first way, the PT teacher blows a whistle and everyone changes from one long line to four rows at once. That is a breakpoint: at a set width, a media query changes the rules.
In the second way, students simply fill the ground: when a row is full, the next student starts a new row. Nobody blows a whistle. That is an intrinsic layout: flex-wrap and flex-basis let the content decide.
| Breakpoint (media query) | Intrinsic (wrap + basis) | |
|---|---|---|
| Who decides | You, at fixed screen widths | The browser, from the space available |
| Good for | Big changes: direction, alignment, hiding a part | Rows of similar items, side panels |
| Reacts to | The screen (viewport) | The container's own width |
| Risk | Breakpoints that do not match your content | Less exact control |
Real layouts use both. Start intrinsic, and add a breakpoint only where the design really needs to change.
Step 1: change direction at a breakpoint
The most common responsive Flexbox change is flex-direction. On a phone, a photo sits above its text (column). On a wider screen, they sit side by side (row).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Direction change</title>
<style>
body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; }
.notice {
display: flex;
flex-direction: column;
gap: 1rem;
max-width: 50rem;
padding: 1rem;
border: 1px solid #c7d2fe;
border-radius: 10px;
}
.notice img { width: 100%; height: auto; border-radius: 6px; }
.notice h2 { margin: 0 0 0.5rem; }
.notice p { margin: 0 0 0.5rem; }
@media (min-width: 36rem) {
.notice { flex-direction: row; align-items: center; }
.notice img { flex: 0 0 40%; width: auto; }
}
</style>
</head>
<body>
<article class="notice">
<img src="https://course.ethicscomputer.in/assets/samples/landscape-400.svg" alt="School ground with the annual day stage" width="400" height="250">
<div>
<h2>Annual Day on 20 December</h2>
<p>Parents of Classes 1 to 8 are invited to the school ground in Rohtak at 10 am.</p>
<p>Entry passes: collect from the class teacher by Friday.</p>
</div>
</article>
</body>
</html>On a narrow preview the picture sits on top, full width. Widen it past 36rem and the picture moves to the left, taking 40% of the card, with the text centred beside it.
Look at what changed inside the media query, besides the direction:
align-items. In a column, the defaultstretchmakes items full width, which is what we want. In a row,stretchwould make the picture as tall as the text.centerlines them up neatly instead.- The item's size.
width: 100%made sense in a column. In a row,flex: 0 0 40%sets the width along the new main axis.
This is the key idea: when you flip the direction, the main axis and cross axis swap. Every property tied to an axis (justify-content, align-items, flex-basis) now works in the other direction, so check each one.
Step 2: wrap and basis patterns without media queries
You saw flex: 1 1 10rem for wrapping cards in Flex Wrap and the drop-below sidebar in Sidebar Layout Design. Here are two more intrinsic patterns, side by side.
The plain wrap row has a weakness: with three items, you often get two on the first line and one stretched alone on the second. The switcher pattern avoids that. All items sit in one row, or all stack in one column, never anything in between.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Wrap row and switcher</title>
<style>
body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; }
h2 { font-size: 1rem; margin: 1rem 0 0.5rem; }
.plans { display: flex; flex-wrap: wrap; gap: 1rem; }
.plans > * {
margin: 0;
padding: 1rem;
border-radius: 8px;
background: #ecfccb;
text-align: center;
}
.wrap-row > * { flex: 1 1 12rem; }
.switcher > * { flex-grow: 1; flex-basis: calc((40rem - 100%) * 999); }
</style>
</head>
<body>
<h2>Plain wrap: flex 1 1 12rem</h2>
<div class="plans wrap-row">
<p>Monthly<br><strong>₹199</strong></p>
<p>Quarterly<br><strong>₹549</strong></p>
<p>Yearly<br><strong>₹1,999</strong></p>
</div>
<h2>Switcher: all in a row, or all stacked</h2>
<div class="plans switcher">
<p>Monthly<br><strong>₹199</strong></p>
<p>Quarterly<br><strong>₹549</strong></p>
<p>Yearly<br><strong>₹1,999</strong></p>
</div>
</body>
</html>Drag the preview width slowly. In a middle range of widths, the plain row shows two plans on top and one wide plan below. The switcher never does that: it jumps from three in a row straight to three stacked, when its container gets narrower than 40rem.
How does calc((40rem - 100%) * 999) do that? Here 100% is the container's width.
- Container wider than 40rem.
40rem - 100%is negative, so the result is a big negative number.flex-basiscannot be negative, so the browser clamps it to0. Every item starts at zero andflex-grow: 1shares the row equally. - Container narrower than 40rem. The result is a huge positive number. Each item wants to be wider than the container, so each one wraps onto its own line and shrinks to full width.
There is no media query, so the switch follows the container, not the screen. The same component switches at the right moment in a wide main column or a narrow sidebar.
Step 3: order at breakpoints, and its cost
You may want a different order on different screens: say, a "Today's offer" box above the menu on phones but beside it on desktop. order inside a media query can do it. But as Flex Order & Alignment explained, keyboard focus and screen readers follow the HTML, not order.
A responsive layout makes this cost bigger:
- The mismatch appears only at some widths. You test on your laptop, Tab order looks right, and the bug exists only on phones.
- People zoom. At 200% zoom a laptop browser shows the phone layout, so desktop users meet the phone order too.
- More combinations to test. Every breakpoint with an
orderchange is another Tab order to check.
Safer choices, in this order:
- Write the HTML in the order that makes sense for reading, and design every breakpoint around it.
- If the order must change, change only items with no links, buttons or fields inside.
- Test with the Tab key at every breakpoint.
flex-direction: row-reverse and column-reverse have the same problem: they reverse the picture, not the HTML.
Step 4: tune the gap
gap is part of the wrapping maths. With flex: 1 1 12rem and a 1rem gap, three items need 36rem plus 2rem of gaps (plus any padding) before they fit on one line. A bigger gap makes items wrap earlier.
On phones, space is precious and a large gap wastes it. On desktop, a small gap looks cramped. You can adjust it in two ways:
/* At breakpoints, through a custom property */
.cards { --gap: 0.75rem; gap: var(--gap); }
@media (min-width: 48rem) { .cards { --gap: 1.5rem; } }
/* Fluid, with no breakpoint */
.cards { gap: clamp(0.75rem, 2.5vw, 1.5rem); }The second version grows smoothly with the viewport, between a minimum of 0.75rem and a maximum of 1.5rem, as you learned in clamp() & Fluid Typography. You can also set row-gap and column-gap separately: wrapped lines often need less space between them than items on the same line.
Step 5: a holy-grail layout that stacks
The holy grail layout is the classic web page: a header, three columns (navigation, main content, a sidebar), and a footer. It got its name because it was very hard to build well before Flexbox and Grid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Holy grail with Flexbox</title>
<style>
body {
margin: 0;
font-family: system-ui, sans-serif;
display: flex;
flex-direction: column;
min-height: 100vh;
min-height: 100dvh;
}
header, footer { padding: 1rem; background: #1e3a8a; color: white; }
.middle {
flex: 1;
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.middle > * { padding: 1rem; border-radius: 8px; }
nav { background: #e0e7ff; }
main { background: #f8fafc; border: 1px solid #e2e8f0; }
aside { background: #fef9c3; }
nav ul { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; margin: 0; padding: 0; list-style: none; }
@media (min-width: 48rem) {
.middle { flex-direction: row; }
nav { flex: 0 0 11rem; }
main { flex: 1; min-width: 0; }
aside { flex: 0 0 14rem; }
nav ul { flex-direction: column; }
}
</style>
</head>
<body>
<header><strong>Jaipur Cricket News</strong></header>
<div class="middle">
<nav aria-label="Sections">
<ul>
<li><a href="#">Ranji Trophy</a></li>
<li><a href="#">IPL</a></li>
<li><a href="#">School cricket</a></li>
</ul>
</nav>
<main>
<h1>Rajasthan win by 5 wickets</h1>
<p>Chasing 241 at Sawai Mansingh Stadium, the home side got there with two overs to spare.</p>
</main>
<aside><h2>Scorecard</h2><p>RAJ 244/5 (48 ov)</p></aside>
</div>
<footer>Contact the sports desk</footer>
</body>
</html>On a narrow preview everything stacks: header, a compact row of section links, the article, the scorecard and the footer. Past 48rem the middle becomes three columns, and the section links turn into a vertical list. On a short page the footer still sits at the bottom of the screen.
What each part does:
- The body is a column with
min-height: 100dvh, and.middlehasflex: 1, so it takes the leftover height and pushes the footer down. This is the flex version of the sticky footer from Header & Footer Layouts. - The side columns have fixed bases (
flex: 0 0 11remand14rem), andmaingetsflex: 1, so only the main column grows. min-width: 0onmainlets it shrink below the width of its longest word or widest table, which a flex item normally refuses to do. Without it, a long URL can push the sidebar off screen.- No
order. The HTML is header, nav, main, aside, footer, which is a sensible reading order at every width.
You will build the same page with grid-template-areas in Responsive CSS Grid. For a whole page skeleton Grid is often neater, because it controls rows and columns together. Flexbox is the better fit when the parts should size from their content.
Common mistakes
- Flipping
flex-directionand forgetting the axes.justify-contentandalign-itemsswap jobs. Recheck them inside the media query. - A wrap row where the last item stretches alone. Use the switcher or a Grid when items must stay equal.
- Reordering links with
orderat one breakpoint. Change the HTML order instead. - Forgetting
min-width: 0on a growing flex item. Long words or tables make it overflow. - Fixed pixel widths on flex items.
width: 300pxon three items breaks below 900px. Useflex-basiswith grow and shrink.
Interview questions
1. How do you make a row of flex items stack on mobile?
Either use flex-direction: column by default and switch to row inside a min-width media query, or let them wrap with flex-wrap: wrap and a flex-basis. The media query gives exact control; wrapping adapts to the container without breakpoints.
2. What changes when you switch flex-direction from column to row?
The main and cross axes swap. justify-content now works horizontally and align-items vertically, and flex-basis now sets width instead of height. Default stretch alignment may suddenly make items as tall as their tallest sibling.
3. Why is changing order at a breakpoint risky?
Keyboard focus and screen readers follow the DOM order, so the visual and focus order differ only at some widths. That bug is easy to miss when testing at one size, and zoomed desktop users see the mobile layout too. Prefer fixing the HTML order.
4. Explain flex-basis: calc((40rem - 100%) * 999).
100% is the container width. When the container is wider than 40rem, the result is negative and is clamped to zero, so the items share one row. When it is narrower, the result is huge, so every item wraps onto its own line. It switches all items at once, based on the container rather than the viewport.
5. Why add min-width: 0 to a flex item?
A flex item's automatic minimum width is its content's minimum size, so it will not shrink below a long word, URL or wide table. min-width: 0 removes that floor and lets the item shrink, so the content can wrap or scroll instead of overflowing the layout.
Key points
- Flexbox responds through breakpoints (media queries) or intrinsically (
flex-wrapplusflex-basis); start intrinsic. - Switching
flex-directionswaps the axes, so recheck alignment and sizes in the same media query. - The switcher,
flex-basis: calc((40rem - 100%) * 999), puts all items in one row or all in one column. orderand the reverse directions change only the picture; responsive layouts make the mismatch harder to spot.gapaffects when items wrap; tune it with a custom property at breakpoints or withclamp().- A flex holy grail: body as a column with
min-height: 100dvh, a middle row with fixed side bases andmin-width: 0on main.
Exercise
Build a contact section for "Isha's Yoga Studio, Pune" with three boxes: Address, Timings and Phone. Use the switcher pattern so the boxes sit in one row when the section is wider than 35rem and stack otherwise. Above the boxes, put a photo and an intro paragraph that stack on phones and sit side by side from 40rem, with the photo taking 35% of the width. Use a fluid gap between 0.75rem and 1.5rem.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Yoga studio contact</title>
<style>
body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; }
.intro { display: flex; flex-direction: column; gap: clamp(0.75rem, 2.5vw, 1.5rem); }
.intro img { width: 100%; height: auto; border-radius: 8px; }
@media (min-width: 40rem) {
.intro { flex-direction: row; align-items: center; }
.intro img { flex: 0 0 35%; width: auto; }
}
.contact { display: flex; flex-wrap: wrap; gap: clamp(0.75rem, 2.5vw, 1.5rem); margin-top: 1.5rem; }
.contact > * { flex-grow: 1; flex-basis: calc((35rem - 100%) * 999); margin: 0; padding: 1rem; border-radius: 8px; background: #f0fdf4; }
</style>
</head>
<body>
<section class="intro">
<img src="https://course.ethicscomputer.in/assets/samples/landscape-400.svg" alt="Studio hall with yoga mats" width="400" height="250">
<p>Morning and evening batches for beginners and seniors, near FC Road.</p>
</section>
<section class="contact">
<p><strong>Address</strong><br>FC Road, Pune</p>
<p><strong>Timings</strong><br>6 am to 8 pm</p>
<p><strong>Phone</strong><br>98220 12345</p>
</section>
</body>
</html>The intro uses a media query because it changes direction and alignment. The contact boxes use the switcher, so they never end up two on one line and one below, and they react to the section's own width.
Quick Quiz
1. You switch a card from flex-direction: column to row. The image suddenly becomes as tall as the text. Why?
In a row the cross axis is vertical, so the default stretch makes items as tall as the line.
2. In flex-basis: calc((40rem - 100%) * 999), what does 100% refer to?
Percentages in flex-basis resolve against the container, which is why the switcher follows the container, not the screen.
3. Which is the safest way to show a block in a different place on phones?
Focus and screen readers follow the HTML, so the HTML order should be the meaningful one.
4. A long URL in main pushes the sidebar off screen in a flex row. What fixes it?
Flex items do not shrink below their content's minimum size unless you set min-width: 0.
Learn CSS with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
