8 / 9 · Basic
Responsive design with media queries
Without one meta tag, many phones lay a page out as if the screen were much wider (MDN gives 980 pixels as an example) and then shrink it, so a media query for phones never runs.
Jump to the 10 practice questionsYou will learn
- Add the viewport meta tag and fluid images
- Write mobile-first media queries with min-width
- Pick breakpoints by content and respect reader settings
Before this: Grid basics
1Explain
One page, every screen
Responsive design means building one page that adapts to whatever screen it lands on, from a narrow phone to a wide monitor, instead of making a separate mobile site. It rests on three ideas: a layout made of flexible widths instead of fixed ones, media that scale inside their containers, and media queries that adjust the layout at the points where it stops working.
The same HTML at 390 and 1280 pixels: stacked on the phone, a sidebar and two columns on the wide screen.
2Problem
Without the viewport tag
Many phones render pages in a virtual viewport wider than the screen, MDN gives 980 pixels as an example, and then shrink the result, because older sites were built for desktops. For a page that is designed to adapt, this gets in the way: a media query that should switch on below 600 pixels never runs, because the browser thinks the screen is 980 pixels wide.
Why do phone media queries fail without the viewport meta tag?
Hint
The phone pretends to be about 980 pixels wide.
Solution
Answer: The phone lays out the page at a wide virtual width
With a 980px virtual viewport, a max 600px query is never true.
3Explore
Fluid widths and images
Fixed widths are the most common cause of sideways scrolling on phones. Prefer max-width to width: max-width: 70rem on a page wrapper lets it fill a small screen and stop growing on a large one. Images keep their natural pixel size by default, so a 1200 pixel photo spills out of a 390 pixel screen. img { max-width: 100%; height: auto; } lets images shrink to fit their container while keeping their proportions.
Without a rule the 1200px picture spills out. max-width: 100% keeps it inside, and height: auto keeps its shape.
Tap a choice: the code and the preview change together.
<style>
img { }
</style>
<div style="border: 1px solid #ccc; padding: 8px">
<img src="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%271200%27 height=%27200%27%3E%3Crect width=%271200%27 height=%27200%27 fill=%27%23d9a35b%27/%3E%3C/svg%3E" width="1200" height="200" alt="A long loaf">
</div>Nothing is drawn: there is no visible content.
4Problem
Images on narrow screens
Which rule stops large images from spilling out of narrow screens?
Hint
The image may shrink but not grow past its box.
Solution
Answer: img { max-width: 100%; height: auto; }
The image shrinks to its container and keeps its proportions.
5Explain
Media queries
A media query wraps rules that apply only when a condition is true. @media (min-width: 600px) { ... } applies its rules when the viewport is at least 600 pixels wide. The usual approach is mobile first: write the base styles for a narrow screen, which are often the simplest (one column, everything stacked), and then add min-width queries that rearrange things as space grows.
The preview box is narrow. Change 300px to 600px and the query stops matching, so the cards stack in one column.
<style>
.cols { display: grid; gap: 12px; }
.cols div { background: #e8eefa; padding: 12px; }
@media (min-width: 300px) {
.cols { grid-template-columns: 1fr 1fr; }
}
</style>
<div class="cols"><div>Bread</div><div>Cakes</div><div>Coffee</div><div>Visit</div></div>6Problem
When min-width: 600px applies
When does @media (min-width: 600px) apply?
Hint
min means "at least".
Solution
Answer: When the viewport is 600px wide or wider
min-width means at least.
7Problem
Mobile first
What does mobile first mean?
Hint
Start with the narrow layout.
Solution
Answer: Write base styles for narrow screens, then add min-width queries
One page; queries add complexity only as space grows.
8Problem
clamp() on a wide screen
font-size: clamp(1.5rem, 4vw, 2.5rem) on a 1600px wide screen with 16px rem. What is the size?
px
Hint
4vw of 1600px is larger than the maximum.
Solution
Answer: 40 px
4vw = 64px, which is above the 2.5rem = 40px maximum, so it stops at 40px.
9Practice
Stop the spill
The 1200px picture spills out of its box. Add the viewport meta tag (width=device-width) to the head, and a rule that makes images max-width: 100% with height: auto.
- viewport meta
- img max-width 100%
- height: auto
<head>
<meta charset="utf-8">
<style>
.hero { border: 1px solid #ccc; padding: 8px; }
</style>
</head>
<body>
<div class="hero">
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1200' height='300'%3E%3Crect width='1200' height='300' fill='%23d9a35b'/%3E%3C/svg%3E" width="1200" height="300" alt="A long loaf on a wooden board">
</div>
</body>Hint
Two changes: one meta line in head, one rule in style.
A solution
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.hero { border: 1px solid #ccc; padding: 8px; }
.hero img { max-width: 100%; height: auto; }
</style>
</head>
<body>
<div class="hero">
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1200' height='300'%3E%3Crect width='1200' height='300' fill='%23d9a35b'/%3E%3C/svg%3E" width="1200" height="300" alt="A long loaf on a wooden board">
</div>
</body>10Practice
One column, then two
Make .cols a grid with a 16px gap. Use one column below 300px and two equal columns at 300px or wider (a min-width: 300px media query with grid-template-columns: 1fr 1fr does this). Check both preview widths.
- grid base
- 16px gap
- a media query
- min-width (mobile first)
- Two columns at 500px and one column at 280px
<style>
.cols div { background: #e8eefa; padding: 12px; }
/* 1. base: .cols is a grid with a 16px gap (one column) */
/* 2. from 300px: two equal columns */
</style>
<div class="cols">
<div>Bread</div>
<div>Cakes</div>
<div>Coffee</div>
<div>Visit</div>
</div><script>(function () {
var cols = document.querySelector('.cols');
if (!cols) return;
cols.removeAttribute('data-responsive-pass');
var done = {}, frames = {}, widths = [280, 500];
window.addEventListener('message', function (event) {
var d = event.data || {};
if (d.type !== 'edubun-columns' || !frames[d.width] || event.source !== frames[d.width].contentWindow) return;
done[d.width] = d.ok;
if (done[280] && done[500]) cols.setAttribute('data-responsive-pass', 'true');
});
var styles = Array.from(document.querySelectorAll('style')).map(function (n) { return n.textContent; }).join('\n');
widths.forEach(function (width) {
var frame = document.createElement('iframe');
frames[width] = frame;
frame.title = 'Layout check ' + width;
frame.setAttribute('aria-hidden', 'true');
frame.tabIndex = -1;
frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:' + width + 'px;height:300px;border:0;visibility:hidden';
var measure = function (width) {
var n = document.querySelector('.cols'), cs = getComputedStyle(n);
var items = Array.from(n.children).map(function (e) { return e.getBoundingClientRect(); });
var columns = cs.gridTemplateColumns.trim().split(/\s+/).filter(Boolean).length;
var equal = width === 280 || Math.abs(items[0].width - items[1].width) < 1;
var rows = width === 280 ? items[1].top > items[0].top : Math.abs(items[0].top - items[1].top) < 1 && items[1].left > items[0].left;
parent.postMessage({type:'edubun-columns',width:width,ok:cs.display === 'grid' && cs.rowGap === '16px' && cs.columnGap === '16px' && columns === (width === 280 ? 1 : 2) && equal && rows}, '*');
};
frame.srcdoc = '<!doctype html><meta charset="utf-8"><style>' + styles + '</style>' + cols.outerHTML + '<script>(' + measure.toString() + ')(' + width + ')<' + '/script>';
document.body.appendChild(frame);
});
})();</script>Hint
The base rule has one column; the min-width query adds the second.
A solution
<style>
.cols div { background: #e8eefa; padding: 12px; }
/* 1. base: .cols is a grid with a 16px gap (one column) */
/* 2. from 300px: two equal columns */
.cols { display: grid; gap: 16px; }
@media (min-width: 300px) {
.cols { grid-template-columns: 1fr 1fr; }
}
</style>
<div class="cols">
<div>Bread</div>
<div>Cakes</div>
<div>Coffee</div>
<div>Visit</div>
</div><script>(function () {
var cols = document.querySelector('.cols');
if (!cols) return;
cols.removeAttribute('data-responsive-pass');
var done = {}, frames = {}, widths = [280, 500];
window.addEventListener('message', function (event) {
var d = event.data || {};
if (d.type !== 'edubun-columns' || !frames[d.width] || event.source !== frames[d.width].contentWindow) return;
done[d.width] = d.ok;
if (done[280] && done[500]) cols.setAttribute('data-responsive-pass', 'true');
});
var styles = Array.from(document.querySelectorAll('style')).map(function (n) { return n.textContent; }).join('\n');
widths.forEach(function (width) {
var frame = document.createElement('iframe');
frames[width] = frame;
frame.title = 'Layout check ' + width;
frame.setAttribute('aria-hidden', 'true');
frame.tabIndex = -1;
frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:' + width + 'px;height:300px;border:0;visibility:hidden';
var measure = function (width) {
var n = document.querySelector('.cols'), cs = getComputedStyle(n);
var items = Array.from(n.children).map(function (e) { return e.getBoundingClientRect(); });
var columns = cs.gridTemplateColumns.trim().split(/\s+/).filter(Boolean).length;
var equal = width === 280 || Math.abs(items[0].width - items[1].width) < 1;
var rows = width === 280 ? items[1].top > items[0].top : Math.abs(items[0].top - items[1].top) < 1 && items[1].left > items[0].left;
parent.postMessage({type:'edubun-columns',width:width,ok:cs.display === 'grid' && cs.rowGap === '16px' && cs.columnGap === '16px' && columns === (width === 280 ? 1 : 2) && equal && rows}, '*');
};
frame.srcdoc = '<!doctype html><meta charset="utf-8"><style>' + styles + '</style>' + cols.outerHTML + '<script>(' + measure.toString() + ')(' + width + ')<' + '/script>';
document.body.appendChild(frame);
});
})();</script>11Explain
Common mistakes
<div style="width: 500px; background: #e8eefa; padding: 8px">A box fixed at 500px is wider than many phones.</div><div style="max-width: 500px; background: #e8eefa; padding: 8px">With max-width the box can shrink on a narrow screen.</div>A fixed width forces sideways scrolling on narrow screens. max-width keeps the limit and still lets the box shrink.
12
Summary
- Add the viewport meta tag; never block zoom.
- Fluid widths, max-width instead of width, img { max-width: 100%; height: auto; }.
- Mobile first with min-width queries at content breakpoints; also prefers-color-scheme, prefers-reduced-motion, print and clamp().