Building Responsive Layouts Using Flexbox and Media Queries
Quick Answer: Build the layout for small screens first, usually as a column. Then use a media query such as @media (min-width: 600px) to change the flex container to a row when there is room. Add <meta name="viewport" content="width=device-width, initial-scale=1"> to the page so phones report their real width. Change the container (flex-direction, gap) instead of every item, and let flex-grow share the space. Choose breakpoints where your layout starts to break, not at fixed device sizes.
S1. Why Do We Need Responsive Flex Layouts?
Imagine a page with a sidebar and a main content area. On a 600px wide screen, the sidebar is 200px wide and the main area is 400px wide. It looks good.
Now someone opens the same page on a 360px wide phone. The two columns cannot keep their sizes, because 600px of layout does not fit in 360px of screen.
Would you build a second page just for phones? That doubles the work, and the two versions drift apart as soon as the content changes.
CSS Flexbox, together with media queries, solves this with one page and several layout states. Let's first see what happens with a fixed design.
S2. The Problem: A Layout That Only Fits One Screen
Fixed layout = a layout whose item sizes are written for one screen width and never change.
Imagine a flex container as wide as a 360px phone screen. It holds a sidebar with a width of 200px and a main area with a width of 400px, both 40px tall, in a row.
Example 1: A desktop design opened on a phone
Assumption: In the output diagrams, one character is about 20px wide and one row is about 20px tall. The layout fills the full width of the viewport. S and M stand for Sidebar and Main.
<!-- HTML -->
<div class="layout">
<aside class="sidebar">Sidebar</aside>
<main class="main">Main</main>
</div>
/* CSS */
.layout { display: flex; }
.sidebar {
width: 200px;
height: 40px;
}
.main {
width: 400px;
height: 40px;
}
Expected output
Viewport 360px wide (18 characters): |SSSSSSMMMMMMMMMMMM| |SSSSSSMMMMMMMMMMMM| Free space = 360 - (200 + 400) = -240px, so the items must shrink. The default flex-shrink is 1, so both shrink in proportion to their base sizes. Sidebar = 200 - 80 = 120px, and Main = 400 - 160 = 240px. Both columns fit, but both are much narrower than designed.
The page renders, but it is not a good phone layout. The same two columns are squeezed side by side.
What goes wrong?
- Cramped columns: The sidebar loses 40% of its width, and the main text becomes narrow and hard to read.
- Overflow risk: A flex item cannot shrink below the size of its content, so long words, images or tables can make the page wider than the screen.
- Duplicated pages: Developers build a separate mobile version, and then must keep both in sync.
- Script hacks: JavaScript measures the window and rewrites styles, which adds code for something CSS can do.
- Unclear intent: Pixel widths for one screen do not say how the layout should behave on others.
Now think about a whole website with navigation, card rows and sidebars. Without a plan for small screens, every part needs its own workaround.
Remember: Flexbox is not broken. It shrinks the items to fit, exactly as it should. The real problem is that nobody told the layout to change its structure when the screen gets narrow.
Animation 1: How a fixed layout gets squeezed
Two columns, one narrow screen
The red highlights show both columns squeezed to fit.
The animation highlights the columns that lose width on a small screen.
S3. The Solution: Change the Container with a Media Query
Flexbox gives us a simpler design.
media query = a CSS condition that applies a block of rules only when the screen matches, for example when the viewport is at least 600px wide.
responsive layout = a layout that adapts its structure to the space it has.
Instead of squeezing the columns, change how the container arranges them.
- The base rules make the container a column, so the sidebar and the main area stack on small screens.
@media (min-width: 600px)changes the container to a row when there is room.- The HTML stays the same, and
flex-growshares the remaining space in the row.
Now the phone gets a stacked layout, and a 600px screen gets two columns.
Example 2: A column on phones and a row from 600px
Assumption: This example uses standard CSS supported by all modern browsers. The meta tag goes inside the head of the page.
<!-- HTML -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<div class="layout">
<aside class="sidebar">Sidebar</aside>
<main class="main">Main</main>
</div>
/* CSS */
.layout {
display: flex;
flex-direction: column;
}
.sidebar, .main { height: 40px; }
@media (min-width: 600px) {
.layout { flex-direction: row; }
.sidebar { width: 200px; }
.main { flex-grow: 1; }
}
Expected output
Viewport 360px wide (18 characters): |SSSSSSSSSSSSSSSSSS| |SSSSSSSSSSSSSSSSSS| |MMMMMMMMMMMMMMMMMM| |MMMMMMMMMMMMMMMMMM| Viewport 600px wide (30 characters): |SSSSSSSSSSMMMMMMMMMMMMMMMMMMMM| |SSSSSSSSSSMMMMMMMMMMMMMMMMMMMM| Below 600px, the container is a column, and both items fill the full width. At 600px, it becomes a row. Sidebar is 200px, and Main takes the other 400px.
Notice the difference. One HTML file produces both layouts, and only the container's direction changes.
Animation 2: The responsive design
One page, two layout states
The base rules serve small screens, and the media query adds the row.
The animation highlights the base layout and the rule that changes it at 600px.
Compare both approaches
| Fixed layout | With media queries |
|---|---|
| The same layout on every screen. | The layout adapts to the screen width. |
| Columns are squeezed on small screens. | Columns stack when there is not enough room. |
| A separate mobile page or script hacks. | One HTML file with several CSS states. |
| Changes need many width edits. | One rule on the container changes the structure. |
| Layout intent is hidden in pixel values. | Layout intent is readable: a row from 600px. |
The idea to remember
- Viewport meta tag = tells phones to use their real screen width, so media queries match what the person sees.
- Media query = a condition, such as
(min-width: 600px), that switches a block of rules on and off. - Mobile-first = write the small-screen layout as the base, then add
min-widthqueries for larger screens. - Change the container = switch
flex-directionorgapon the container, and let flex properties share the space. - Content-based breakpoints = add a breakpoint where the layout starts to look wrong, not at a list of device sizes.
S4. Step-by-Step Code Breakdown
1. Know the common media query conditions
A media query wraps rules in @media (condition) { ... }. The rules inside apply only while the condition is true. Widths are measured in CSS pixels. Browser zoom changes them, so a page zoomed to 200% can match a narrower breakpoint.
For the browser to report the real screen width on phones, the page needs the viewport meta tag from Example 2. Without it, many mobile browsers lay the page out at a wider virtual width, and your width-based rules do not behave as expected.
| Condition | It matches when | Typical use |
|---|---|---|
(min-width: 600px) |
The viewport is 600px wide or wider | Mobile-first layouts |
(max-width: 599px) |
The viewport is 599px wide or narrower | Desktop-first layouts |
(orientation: landscape) |
The viewport is wider than it is tall | Adjusting a layout on rotated phones |
(prefers-reduced-motion: reduce) |
The person asked the system for less motion | Turning off animations |
2. Write mobile-first
In a mobile-first stylesheet, the base rules describe the smallest layout, and each min-width query adds changes for larger screens. Here a navigation bar is stacked on phones. From 600px it becomes a row, and an auto margin pushes Login to the far end.
Example 3: A navigation bar that stacks and then spreads
<!-- HTML -->
<nav class="nav">
<div class="nav-item">Logo</div>
<div class="nav-item">Menu</div>
<div class="nav-item login">Login</div>
</nav>
/* CSS */
.nav {
display: flex;
flex-direction: column;
}
.nav-item {
height: 40px;
background: #E2E8F0;
}
@media (min-width: 600px) {
.nav { flex-direction: row; }
.nav-item { width: 100px; }
.login { margin-left: auto; }
}
Expected output
Viewport 600px wide (30 characters): |AAAAABBBBB CCCCC| |AAAAABBBBB CCCCC| A is Logo, B is Menu and C is Login. Free space = 600 - 300 = 300px, and the auto margin on Login takes all of it. Login moves to the far end, and Logo and Menu stay together at the start. Viewport 360px wide: The three items are stacked in the HTML order. Each one is 360px wide and 40px tall.
3. Adapt the gap and the item sizing together
A media query can change several container properties at once. Here three cards are stacked with a 10px gap on phones. From 600px they become equal columns with a 20px gap, using flex: 1.
Example 4: Cards that become equal columns
/* CSS (three .card elements inside .cards) */
.cards {
display: flex;
flex-direction: column;
gap: 10px;
}
.card {
height: 40px;
background: #E2E8F0;
}
@media (min-width: 600px) {
.cards {
flex-direction: row;
gap: 20px;
}
.card { flex: 1; }
}
Expected output
Viewport 640px wide (32 characters): |AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC| |AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC| A, B and C are the three cards. Free space = 640 - (20 + 20) = 600px, shared equally by flex: 1. Each card is 200px wide. Viewport 360px wide: The cards are stacked, each 360px wide and 40px tall. Total height = 3 x 40 + 2 x 10 = 140px.
4. Show or hide a part of the layout
Sometimes a part of the page only makes sense when there is room for it. display: none removes an element from the layout, and a flex item that is removed takes no space. Use this only for content that is not essential, because hidden content is also hidden from screen readers.
Example 5: A sidebar that appears from 600px
/* CSS (same HTML as Example 2) */
.layout { display: flex; }
.sidebar { display: none; }
.main {
flex-grow: 1;
height: 40px;
}
@media (min-width: 600px) {
.sidebar {
display: block;
width: 120px;
height: 40px;
}
}
Expected output
Viewport 360px wide (18 characters): |MMMMMMMMMMMMMMMMMM| |MMMMMMMMMMMMMMMMMM| Viewport 600px wide (30 characters): |SSSSSSMMMMMMMMMMMMMMMMMMMMMMMM| |SSSSSSMMMMMMMMMMMMMMMMMMMMMMMM| Below 600px, the sidebar is not rendered, and Main fills the whole row. At 600px, Sidebar is 120px, and Main takes the other 480px.
5. Add breakpoints where the layout needs them
You can use more than one breakpoint. Add each one at the width where the current layout starts to look wrong, and keep the number small. In this example, the layout is a column under 600px, two columns from 600px, and three columns from 800px.
Example 6: A layout with two breakpoints
<!-- HTML -->
<div class="layout">
<aside class="sidebar">Sidebar</aside>
<main class="main">Main</main>
<aside class="extra">Extra</aside>
</div>
/* CSS */
.layout {
display: flex;
flex-direction: column;
}
.sidebar, .main, .extra { height: 40px; }
.extra { display: none; }
@media (min-width: 600px) {
.layout { flex-direction: row; }
.sidebar { width: 160px; }
.main { flex-grow: 1; }
}
@media (min-width: 800px) {
.extra {
display: block;
width: 160px;
}
}
Expected output
Viewport 600px wide (30 characters): |SSSSSSSSMMMMMMMMMMMMMMMMMMMMMM| |SSSSSSSSMMMMMMMMMMMMMMMMMMMMMM| Viewport 800px wide (40 characters): |SSSSSSSSMMMMMMMMMMMMMMMMMMMMMMMMEEEEEEEE| |SSSSSSSSMMMMMMMMMMMMMMMMMMMMMMMMEEEEEEEE| S is Sidebar, M is Main and E is Extra. At 600px, Sidebar is 160px, and Main takes the other 440px. At 800px, Extra appears at 160px, and Main shrinks to 480px. Viewport 360px wide: Sidebar and Main are stacked, each 360px wide and 40px tall. Extra is hidden.
The two queries add to each other. At 800px both are true, so the second one builds on top of the first.
S5. Architecture and Real-World Trade-Offs
Responsive rules are written per container, so each part of a page can adapt in its own way. This is useful in navigation bars, card rows and page layouts.
How the design fits a website
Imagine a website with a navigation bar, a row of cards and a sidebar. Each one starts with a small-screen layout and changes at a breakpoint.
A focused responsive flow
Each website area has a base layout and a rule that changes it at a breakpoint.
The animation traces each website area to the media query rule that changes it.
Benefits for larger websites
- One codebase: A single HTML file serves every screen, so content changes happen once.
- Maintainability: The responsive rules sit beside the base rules they change, and the container carries most of the change.
- Readable intent: A rule such as
min-width: 600pxstates when the layout changes. - Safe defaults: The base layout works on the smallest screens, and larger screens only add to it.
- Fewer overrides: Mobile-first means larger screens add rules, instead of undoing many earlier ones.
Important trade-offs
- Media queries respond to the viewport, not to the space around a component. A card placed in a narrow sidebar on a wide screen does not know it is narrow. Container queries (
@container) exist for that case. - Every breakpoint adds CSS and needs testing. Keep the number small.
- Test between breakpoints, with browser zoom and with a larger text size, since both change how much room the layout has.
display: nonehides content from everyone, including screen readers. Hide only content that is not essential.- The
orderproperty changes only the visual order, so use it carefully when you reorder parts for small screens. flex-wrapcan let items move to new lines without a media query. Wrapping and its limits are covered in the next article.
Important: A media query does not change how flexbox works. It only switches which rules are active. Inside each state, the same free-space rules apply, so check the base layout first and then each breakpoint on its own.
S6. Common Mistakes and Best Practices
Mistake 1: Forgetting the viewport meta tag
Wrong: Write careful media queries but leave the meta name="viewport" tag out of the page.
Why it fails: Many mobile browsers then lay the page out at a wider virtual width and scale it down. A phone does not report its real width, so your width-based rules do not match as expected.
Better: Add <meta name="viewport" content="width=device-width, initial-scale=1"> to the head.
Rule: Add the viewport tag before you test any breakpoint.
Mistake 2: Mixing min-width and max-width carelessly
Wrong: Use (max-width: 600px) for one layout and (min-width: 600px) for another.
Why it fails: At exactly 600px both conditions are true, so both blocks of rules apply together and can conflict.
Better: Pick one direction. In a mobile-first stylesheet, use only min-width queries.
Rule: One stylesheet, one direction of queries.
Mistake 3: Changing every item instead of the container
Wrong: Rewrite the width of each item inside the media query to fake a stacked layout.
Why it fails: It repeats the same intent many times, and it breaks as soon as an item is added.
Better: Change flex-direction on the container, and let items share the space with flex-grow.
Rule: Change the container first.
Mistake 4: Putting the media query before the base rule
Wrong: Write the @media block at the top of the file, and the base .layout rule after it.
Why it fails: A media query does not add specificity. When two rules have the same specificity, the later one wins, so the base rule overrides the query.
Better: Write the base rules first, then the media queries after them.
Rule: Base first, queries after.
Mistake 5: Choosing breakpoints from a list of devices
Wrong: Set breakpoints at the screen widths of specific phones and tablets.
Why it fails: Screen sizes vary and keep changing, so the layout can still break at widths between your breakpoints.
Better: Resize the browser, and add a breakpoint where the layout starts to look wrong.
Rule: Let the content choose the breakpoint.
S7. How This Comes Up in Interviews
Question 1: What does the viewport meta tag do, and why do you need it?
What the interviewer wants: They want to know whether you understand how mobile browsers lay out a page.
Strong answer:
"It tells the browser to set the layout width to the device width. Without it, many mobile browsers lay the page out at a wider virtual width and scale it down, so media queries and fluid layouts do not match what the person sees."
Question 2: What is the difference between mobile-first and desktop-first?
Strong answer:
"Mobile-first writes the small-screen layout as the base and uses min-width queries to add changes for larger screens. Desktop-first writes the large layout as the base and uses max-width queries to remove or change things for small screens. I prefer mobile-first because larger screens add rules rather than undoing many earlier ones."
Question 3: How would you make a two-column flex layout stack on small screens?
Strong answer:
"I make the container a column by default, so the two parts stack. Then I add a min-width media query that sets flex-direction to row and gives the columns their widths or flex-grow. The HTML does not change."
Question 4: What is the difference between a media query and a container query?
Strong answer:
"A media query checks the size of the viewport. A container query checks the size of a containing element. Container queries suit components that can be placed in spaces of different widths, and media queries suit page-level layout."
What should different experience levels explain?
- Junior developer: Explain the viewport tag and show a column that becomes a row with one
min-widthquery. - Senior developer: Explain mobile-first, overlapping queries, why the order of rules matters, and how zoom changes which breakpoint matches.
- Technical architect: Explain how a small set of shared breakpoints, and a rule for media queries versus container queries, keep a design system consistent.
S8. Hands-On Practice
Beginner: Stack and spread
Create a flex container with three 40px tall boxes. Make it a column by default, and use @media (min-width: 600px) to change it to a row with flex: 1 on each box. Resize your browser window to see both states.
Expected result: The boxes are stacked below 600px, and they are equal columns from 600px.
Intermediate: Build a responsive navigation bar
Build the navigation bar from Example 3. Then hide the Menu item below 600px with display: none and show it again from 600px.
Hint: Write the hidden state as the base rule, and the visible state inside the media query.
Expected result: On a narrow window, only Logo and Login are visible. From 600px, all three items appear and Login sits at the far end.
Advanced: Find your own breakpoints
Build a layout with a sidebar, a main area and an extra column. Start with a column, then slowly widen the browser window and add a breakpoint only where the layout starts to look wrong. Finally, zoom the page to 200% and check for horizontal scrolling.
Expected result: Each breakpoint is explained by something you saw in the layout. At 200% zoom the page switches to a narrower layout and does not scroll sideways.
S9. Next Steps and Community
Previous article: Nested Flex Containers and Complex Layout Structures.
Next article: Flexbox Overflow, Wrapping and Common Layout Problems.
Continue the series by learning what happens when flex items do not fit, how flex-wrap moves them onto new lines, and how to fix the layout problems that come up most often.
Try the examples in your own HTML and CSS project. Change the breakpoints, switch the base layout between a column and a row, test your pages with browser zoom, and share your layouts with the Upgradix community. Help other developers understand Flexbox through practical examples.
Start small. Add layout only when there is room.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.