Complete Guide to Mobile Responsive Design
Build layouts that work on every screen. Mobile-first breakpoints, Grid, Flexbox, container queries, fluid type and responsive images.
Introduction
A layout that looks perfect on your 1440px monitor can fall apart the moment someone opens it on a 375px phone — columns collapse into unreadable strips, tables push the whole page sideways, and font sizes made for desktop force pinch-to-zoom. Responsive design is the discipline of making one codebase work across that entire range, and modern CSS finally lets you do most of it without a single line of JavaScript.
This guide is about the strategy: how to pick breakpoints, when to reach for Grid vs. Flexbox vs. container queries, how to scale typography fluidly, and how to handle the pieces that usually break first — images, tables, and viewport height. If you want the deep mechanics of Grid and Flexbox themselves, the Complete Guide to CSS Grid and Flexbox covers them property by property; here we focus on using them to build layouts that survive any screen.
Mobile-First Strategy
Mobile-first means your base styles target the smallest screen and you enhance upward with min-width media queries. The alternative — styling for desktop and then overriding downward with max-width — produces more CSS, harder-to-reason-about overrides, and layouts that break in between breakpoints you forgot to test.
/* Base styles — mobile first */
.card {
padding: 1rem;
font-size: 0.875rem;
}
/* Tablet and up */
@media (min-width: 768px) {
.card {
padding: 1.5rem;
font-size: 1rem;
}
}
/* Desktop and up */
@media (min-width: 1024px) {
.card {
padding: 2rem;
font-size: 1.125rem;
}
}
Notice how the mobile version needs the least code: stacked content, full-width elements, readable base size. Larger screens only add what they need. That’s the economic argument for mobile-first — the small screen gets the simplest CSS, and complexity grows only where there’s room for it.
Picking breakpoints
You don’t need a breakpoint for every device on the market — add one when the layout actually stops working: lines too long to read, a grid that cramps its cells, whitespace that turns into a canyon. A pragmatic set that covers most projects:
| Breakpoint | Typical device | What usually changes |
|---|---|---|
| base (0–639px) | Phones | Single column, stacked nav, base font size |
| 640px | Large phones, small tablets | Two-column grids, denser spacing |
| 768px | Tablets | Sidebar appears, nav goes horizontal |
| 1024px | Laptops | Full multi-column layout, max content width |
| 1280px+ | Desktops | Optional: wider gutters, larger type caps |
These numbers follow the Tailwind convention (sm 640, md 768, lg 1024, xl 1280), which is worth adopting even without Tailwind because it gives the whole team a shared vocabulary. What matters is consistency: five breakpoints you actually maintain beat twelve that only exist in a stylesheet nobody opens.
Two breakpoints people forget: landscape phones (~568–812px tall) where a 100vh hero eats the whole screen, and very wide monitors (>1600px) where an uncapped max-width turns paragraphs into 200-character lines.
Choosing the Right Layout Tool
The most common responsive mistake is reaching for a media query when CSS can solve the problem intrinsically. The decision comes down to what should react:
| Situation | Tool | Why |
|---|---|---|
| Header, sidebar, overall page grid | Media queries | Page layout depends on the viewport, not a container |
| Card used in sidebar AND main column | Container queries | Same component, different available width |
| Grid of cards/products | repeat(auto-fit, minmax()) | No breakpoint needed — it fills whatever space exists |
| Font size, padding, section spacing | clamp() | Smooth scaling, no breakpoint jumps |
| Showing/hiding whole sections | Media queries | Structural change tied to screen size |
If you’re unsure which of Grid or Flexbox fits a given layout, the CSS Modern Layout guide compares them pattern by pattern — from here on, we only care about the responsive angle of each.
CSS Grid for Responsive Layouts
Grid shines for two-dimensional page structure. For responsive work you mostly need two patterns — the rest is mechanics covered in the dedicated guide.
The auto-fit grid
This one’s my most-used responsive pattern. It creates as many columns as fit and lets the cards stretch to fill the row — zero media queries:
.auto-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
}
Tune minmax() to the smallest width where your card still reads well. 280px works for text cards; image-heavy cards often need 320px. If cards should never sit alone on a row, switch auto-fit to auto-fill — it keeps the empty tracks, so items keep their size instead of stretching awkwardly.
The classic breakpoint grid
When you want explicit control — exactly 2 columns on tablets, 3 on desktop:
.grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 640px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
Use this when the column count is a design decision, not a function of available space. Marketing pages and dashboards usually want explicit counts; card galleries and listing pages usually want auto-fit.
Rearranging regions with grid areas
grid-template-areas lets you reorder entire page regions at a breakpoint without touching the HTML — put main before nav on mobile so content comes first:
.layout {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 250px;
min-height: 100vh;
}
@media (max-width: 768px) {
.layout {
grid-template-areas:
"header"
"main"
"nav"
"aside"
"footer";
grid-template-columns: 1fr;
}
}
This example uses max-width on purpose: stacking everything under 768px is simpler as a single exception than as three min-width blocks. Mobile-first is a guideline, not a religion — the rule is to pick whichever direction needs fewer declarations.
Flexbox Patterns
Flexbox handles one-dimensional layouts: rows and columns of things. Three patterns cover most responsive needs.
Centering and sticky footers
.center {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
}
The sticky footer pattern keeps the footer at the bottom on short pages without pushing it off-screen on long ones — flex: 1 on main absorbs the leftover space.
Navigation that collapses
.nav {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0 1.5rem;
}
.nav-links {
display: flex;
gap: 1.5rem;
}
@media (max-width: 768px) {
.nav-links {
display: none;
}
}
Two warnings here. First, display: none removes the links from keyboard and screen-reader users too — pair it with a visible menu toggle that reveals them, or you just made your site unnavigable on phones. Second, prefer the <details> element or a disclosure button over a pure-CSS checkbox hack; the hack works, but it breaks focus management and adds no accessibility semantics.
The overflow trap: min-width: 0
Flex children refuse to shrink below their content size by default. A card containing a long URL or a <pre> block will blow out the layout on narrow screens no matter how many breakpoints you write. The fix is one line:
.card {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.card-content {
flex: 1;
min-width: 0; /* lets the child shrink below content size */
}
If a responsive layout “randomly” overflows on phones and you can’t find the fixed-width culprit, this is usually it.
Container Queries
Media queries answer “how wide is the viewport?” Container queries answer “how much room does this component have?” That distinction matters the moment a component lives in more than one context — a card that’s full-width on mobile, half-width in a sidebar, and third-width in a grid.
/* Define a containment context */
.card-container {
container-type: inline-size;
container-name: card;
}
/* Query the container size */
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 120px 1fr;
gap: 1.5rem;
}
}
Give the card’s container 400px or more and it flips to a horizontal layout, whatever the viewport does. Drop the same card into a narrow sidebar and it falls back to stacked on its own. This is what makes container queries the right tool for design systems: the component carries its own responsive behavior instead of depending on page-level breakpoints that know nothing about where it gets placed.
Container query units
Alongside @container you get units relative to the container, not the viewport — cqw (1% of container width) and cqi (1% of inline size). They make truly fluid component internals possible:
.sidebar {
/* scales with the sidebar's own width, not the screen */
font-size: clamp(0.875rem, 3cqw, 1.25rem);
padding: 2cqi;
}
Container queries are supported in all current browsers (baseline since 2023). If you still need a fallback for older ones, ship a sensible min-width media query version first and let @container enhance it — same progressive-enhancement logic as mobile-first. The MDN container queries reference has the full syntax, including style() queries.
Fluid Typography and Spacing
Breakpoints create visible jumps — text that’s comfortable at 767px suddenly oversized at 768px. clamp() removes the jump by interpolating between a minimum and maximum using a viewport-relative preferred value:
h1 {
/* never below 1.5rem, never above 3.5rem, ~5vw in between */
font-size: clamp(1.5rem, 5vw, 3.5rem);
}
p {
font-size: clamp(1rem, 2.5vw, 1.125rem);
}
The formula behind the preferred value: pick the viewport width where you want the minimum to stop applying and the width where the maximum kicks in, then the middle value is min + (max − min) × (100vw − minVw) / (maxVw − minVw). In practice, vw-based values between 2.5vw and 6vw cover most needs — just check the extremes so the preferred value actually lands between the bounds at your design’s target widths.
The same trick works for spacing — honestly, that’s where fluid design earns its keep. Section padding that breathes on desktop but doesn’t waste a phone screen:
.section {
padding: clamp(1rem, 5vw, 4rem);
margin-bottom: clamp(1.5rem, 4vw, 3rem);
}
Apply clamp() to vertical rhythm (section padding, heading margins) before reaching for it on body copy — body text below ~1.25rem rarely benefits from scaling, and an over-enthusiastic vw term can push it under the 16px users expect. MDN’s clamp() page has the full parameter details.
Responsive Images
Images cause two distinct responsive problems — they download too much data for small screens, and they shift layout when dimensions are unknown — and each needs a different fix.
srcset and sizes: resolution switching
<img
src="image-800.jpg"
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w, image-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw"
alt="Description"
width="800"
height="600"
loading="lazy"
decoding="async"
/>
With srcset you list which files exist and their real widths; with sizes you declare how wide the image will render at each viewport — and that’s the part people get wrong. Put them together and the browser fetches the smallest file that still looks sharp. Leave sizes out or get it wrong and it assumes 100vw, so a 300px-wide thumbnail ends up downloading the 1600px file. Write sizes from your actual layout, not from the image: a three-column grid is roughly 33vw on desktop, not 100vw.
picture: art direction
srcset picks resolutions of the same image. When the crop itself should change — a wide landscape on desktop vs. a square on mobile — use picture:
<picture>
<source media="(max-width: 600px)" srcset="mobile.avif" type="image/avif" />
<source media="(max-width: 1200px)" srcset="tablet.avif" type="image/avif" />
<img src="desktop.jpg" alt="Description" width="1600" height="900" />
</picture>
Put modern formats first (avif, then webp) and keep the <img> as the fallback — browsers pick the first <source> they support, so order matters. The <img> is also where alt, dimensions, and loading attributes live; <source> elements only swap the file.
Preventing layout shift
Always declare dimensions — either width/height attributes on the <img> or aspect-ratio in CSS. The browser reserves the box before the file arrives, which kills the CLS jump:
.image-container {
aspect-ratio: 16 / 9;
overflow: hidden;
}
.image-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
For the LCP image specifically (usually the hero), do the opposite of lazy: loading="eager" plus fetchpriority="high". Lazy-loading the hero is a classic self-inflicted LCP regression on mobile. More details in the MDN responsive images guide.
Responsive Tables and Data
Tables are the #1 cause of horizontal overflow on mobile. Two strategies cover almost every case.
Horizontal scroll is the simplest: wrap the table and let it scroll inside the wrapper, so the page itself never overflows:
.table-wrapper {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
Use this for genuinely tabular data — pricing matrices, comparison tables, logs — where columns must stay aligned. The min-width on the table controls when scrolling kicks in.
Card transform converts each row into a stacked card on small screens, repeating the header as a label via data-label:
@media (max-width: 640px) {
table, thead, tbody, th, td, tr {
display: block;
}
thead {
display: none;
}
tr {
margin-bottom: 1rem;
border: 1px solid #e2e8f0;
border-radius: 0.5rem;
padding: 0.75rem;
}
td {
display: flex;
justify-content: space-between;
}
td::before {
content: attr(data-label);
font-weight: 600;
}
}
This needs data-label on every <td> in the markup. It reads far better on phones for entity-style data (user lists, invoices, settings), but it’s the wrong choice for dense comparisons where scanning across columns is the point — a 20-column pricing table should scroll, not stack.
Viewport Units and Safe Areas
100vh on mobile isn’t 100vh. The browser chrome — address bar, toolbars — slides in and out as you scroll, and classic vh picks one value that doesn’t match either state. The result: hero sections with content hidden behind the address bar, or a gap at the bottom. The dynamic viewport units fix this:
dvhtracks the current visible height — resizes as chrome appears/disappears.svhis the smallest viewport height — guaranteed fully visible.lvhis the largest — the height with chrome fully hidden.
.hero {
/* always fully visible, even with the address bar showing */
min-height: 100svh;
}
.drawer {
/* track the live viewport so the drawer never gets cut off */
max-height: 100dvh;
}
Use svh for anything that must never be covered (heroes, full-screen dialogs) and dvh for elements that should track the live viewport (sticky drawers, chat sheets). Plain vh is still fine as the fallback — browsers that don’t know svh/dvh ignore the declaration, so declare vh first.
Notched devices add one more wrinkle. iPhones in landscape can overlay your fixed sidebars on the sensor housing. env(safe-area-inset-*) returns the unsafe margins:
.header {
padding-left: max(1rem, env(safe-area-inset-left));
padding-right: max(1rem, env(safe-area-inset-right));
}
This requires viewport-fit=cover in the viewport meta tag to have any effect — without it the insets are always 0.
Testing on Real Conditions
DevTools device emulation is where everyone starts — Chrome/Firefox Ctrl+Shift+M, Safari’s Responsive Design Mode — and it’s good for layout bugs. What it won’t show you: real GPU performance, actual touch behavior, font rendering differences, and the mobile browser chrome issue from the previous section.
The testing hierarchy that catches most bugs:
- DevTools emulation for layout, breakpoints, and quick iteration.
- Network throttling (Slow 4G preset) — responsive bugs are often really performance bugs: a 2MB hero image that never loads exposes your broken layout-without-image state.
- A real phone on the same Wi-Fi — Chrome DevTools remote debugging for Android, Safari Web Inspector for iOS. Five minutes on a real device finds issues emulators never will: tap targets that are too small, hover-dependent menus, scroll jank.
- Automated viewport tests catch regressions cheaply. With Playwright, asserting no overflow at your breakpoints is a few lines:
test('no horizontal overflow on mobile', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 });
await page.goto('/guides/');
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > document.documentElement.clientWidth
);
expect(overflow).toBe(false);
});
For visual debugging of the layout itself, the classic outline trick still works:
* {
outline: 1px solid red;
}
Ugly, temporary, and instantly shows which element is causing the overflow. Remove it before committing.
Auditing an Existing Layout
When you inherit a codebase that “mostly works on mobile,” don’t rewrite it — audit it in this order:
- Set the viewport meta tag check first.
width=device-width, initial-scale=1missing or wrong? Everything else is moot. - Hunt fixed widths. Search the stylesheet for
width:andmin-width:inpx— each one is a suspect. Replace with%,fr,max-width, orclamp()where it’s a container. - Check the usual overflow culprits: tables without
.table-wrapper,<pre>blocks withoutoverflow-x: auto, long URLs, flex children missingmin-width: 0. - Audit images: are dimensions declared on every one? Any
srcset/sizesabove the fold, andloading="lazy"kept below it? - Check
max-widthmedia queries. If the codebase is desktop-first, you don’t have to rewrite it all at once — but every new feature should be mobile-first, and themax-widthblocks get converted as you touch them. - Tap-test the nav and CTAs at 375px. Buttons under ~44×44px and links closer than ~8px fail both users and WCAG 2.5.5.
- Test with real content, not lorem. A layout that works with 12-character titles breaks with real copy. This is where
auto-fitgrids earn their keep — they degrade gracefully instead of snapping at a breakpoint.
Most “responsive rewrites” turn out to be 10–20 targeted fixes found by exactly this list. Run it before assuming you need a redesign.
Best Practices
- Start mobile-first — base styles target the smallest screen,
min-widthmedia queries enhance upward. - Let CSS do the work —
auto-fitgrids,clamp(), and container queries remove breakpoints instead of adding them. - Write
sizesfrom the layout, not the image — it’s render width, not file width. - Declare image dimensions —
width/heightattributes oraspect-ratioprevent CLS. - Use
svh/dvhovervhfor anything the browser chrome could cover. - Set
min-width: 0on flex children — it’s the fix for most mystery overflow. - Prefer
gapover margins in flex and grid — spacing that doesn’t collapse or double up at edges. - Test on a real phone — emulators miss touch, GPU, and browser-chrome behavior.
- Cap line length — wide screens turn paragraphs into rivers;
max-width: ~70chon text containers keeps them readable. - Keep breakpoints few and consistent — adopt a shared scale (like the 640/768/1024/1280 set) instead of ad-hoc values.
Common Mistakes
- Writing everything with
max-widthmedia queries — desktop-first CSS grows bigger and harder to override. - Fixed pixel widths on containers — breaks on any screen narrower than the value.
- Hiding the nav with
display: noneand offering no alternative — keyboard users lose the menu too. - Missing
sizesonsrcsetimages — the browser defaults to100vwand downloads 4x the needed pixels. - No image dimensions — causes layout shift every load.
100vhheroes on mobile — the address bar covers your CTA; use100svh.- Lazy-loading the LCP image — a direct, self-inflicted LCP regression.
- Table without
overflow-x: autowrapper — one wide table pushes the entire page sideways. - Flex children without
min-width: 0— long content overflows instead of shrinking. - Media queries for component-level responsiveness — the right tool is container queries; page breakpoints don’t know the component’s context.
- Breakpoint per device — you end up chasing a moving market; break where the layout breaks.
See Also
- Complete Guide to CSS Grid and Flexbox — the property-level deep dive this guide references
- CSS Modern Layout: Grid, Flexbox, Container Queries — pattern-by-pattern comparison of the layout systems
- CSS Dark Mode with prefers-color-scheme — media queries beyond screen size
- Web Components Guide — where container queries become essential
Frequently Asked Questions
Should I use container queries or media queries?
Use media queries for page-level layout — header, sidebar, main grid — because those decisions genuinely depend on the viewport. Use container queries for component-level responsiveness — cards, widgets, anything reused in different contexts — because the component should react to the space it gets, not the screen. They answer different questions, so most real projects need both.
What is the difference between auto-fit and auto-fill in CSS Grid?
Both fill the row with as many tracks as fit. The difference is what happens to leftover space: auto-fit collapses empty tracks to zero so existing items stretch and fill the row, while auto-fill keeps the empty tracks so items keep their size and leave gaps. Pick auto-fit when items should grow to fill space; auto-fill when a lone item shouldn't stretch into a giant banner.
How do I handle the mobile viewport height issue?
Mobile browsers show and hide the address bar as you scroll, which changes what vh means. Use 100dvh for elements tracking the live viewport or 100svh for anything that must always be fully visible. Keep a vh declaration first as the fallback for older browsers — the cascade handles the rest.
How many breakpoints should a website have?
Fewer than you think. A common working set is 4–5 (like 640/768/1024/1280 plus an optional wide cap), but the right number is "however many places your layout actually breaks." Every breakpoint is code to maintain and a state to test — if auto-fit, clamp(), or container queries can absorb the variation instead, use them.
Are media queries still needed with container queries?
Yes. Container queries know a component's width, not the viewport's — they can't answer page-level questions like "is there room for a sidebar?" or "is this a phone?" They also can't do prefers-color-scheme, prefers-reduced-motion, or print styles. Media queries handle the page context; container queries handle the component context.
Do I still need media queries for prefers-reduced-motion and dark mode?
Yes — and these count as responsive concerns too. @media (prefers-color-scheme: dark) reacts to the user's theme, @media (prefers-reduced-motion: reduce) reacts to their motion needs, and neither cares about screen size. The dark mode recipe covers a complete implementation.
Related Resources
Web Components — Custom Elements, Shadow DOM & Templates
A practical guide to Web Components: creating reusable custom elements, encapsulating styles with Shadow DOM, and composing with HTML templates.
GuideComplete Guide to React Performance Optimization
Optimize React apps for speed. Covers memoization, virtualization, code splitting, bundle analysis, React Profiler, concurrent features, and Core Web Vitals.
GuideWCAG 2.2 Accessibility: A Developer Guide
A practical guide to WCAG 2.2 compliance: the four POUR principles, ARIA, keyboard navigation, accessible forms and modals, tested with real code examples.