edubun
English
1 / 12

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 questions

You 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.

Rule for img
<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>
Preview

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.

Your code
<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>
Preview

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.

Checks
  • viewport meta
  • img max-width 100%
  • height: auto
Your code
<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>
Preview
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.

Checks
  • grid base
  • 16px gap
  • a media query
  • min-width (mobile first)
  • Two columns at 500px and one column at 280px
Your code
<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>
Preview
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

Mistake
<div style="width: 500px; background: #e8eefa; padding: 8px">A box fixed at 500px is wider than many phones.</div>
Fixed
<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().

Next unitStyle a small page
Full text · The whole lesson as one text

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. Flexbox and grid already do much of the work, as the last two units showed with wrapping cards and auto-fill columns.

The viewport meta 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. <meta name="viewport" content="width=device-width"> in the head tells the browser to use the real width of the device, measured in CSS pixels. Never add user-scalable=no or a low maximum-scale; MDN warns that blocking zoom shuts out people with low vision, and WCAG 1.4.4 expects text to be resizable to 200 percent.

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. WCAG 1.4.10, Reflow, asks that content work at a width of 320 CSS pixels without scrolling in two directions; checking your page in a 320 pixel wide window is a good habit.

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. Choose breakpoints where your content starts to look wrong, not by guessing popular device sizes, since new screen sizes appear every year. Writing breakpoints in em, such as 40em, also makes them respond when a reader enlarges the text.

/* Base: one column for narrow screens */
.cols { display: grid; gap: 16px; }

/* From 600px: two columns */
@media (min-width: 600px) {
  .cols { grid-template-columns: 1fr 1fr; }
}

/* From 960px: a sidebar layout */
@media (min-width: 960px) {
  .cols { grid-template-columns: 240px 1fr 1fr; }
}
Mobile first: base styles, then min-width queries that add columns.
The same HTML at 390 and 1280 pixels: stacked on the phone, a sidebar and two columns on the wide screen.

Other things a query can ask

Media queries can test more than width. The reader preference features come from Media Queries Level 5: (prefers-color-scheme: dark) matches when the reader has chosen a dark theme in the operating system, so you can offer dark colours automatically. (prefers-reduced-motion: reduce) matches when the reader has asked for less motion, often because animation makes them dizzy; turn off large movements and parallax effects inside it. (hover: hover), from Level 4, tells you whether the main pointer can hover, which a touch screen cannot. print styles a page for paper, for example by hiding the menu. Finally, clamp() sizes things smoothly without a query: font-size: clamp(1.5rem, 4vw, 2.5rem) grows with the screen but never goes below 1.5rem or above 2.5rem.

The preview boxes on this page are only about 340 to 530 pixels wide, so the exercise below uses a small 300px breakpoint that you can see working. On a real site, choose breakpoints from your own content, such as 600px or 40em.
Key points
  • 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().

Practice questions from Responsive design with media queries on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (5)
  • W3C CSS Working Group specifications: CSS Snapshot 2025, Selectors Level 4, CSS Cascading and Inheritance Level 5, CSS Color Level 4, CSS Values and Units Level 4, CSS Box Model Level 3, CSS Box Sizing Level 3, CSS Fonts Level 4, CSS Flexible Box Layout Level 1, CSS Grid Layout Level 2, Media Queries Level 4 and Level 5 (w3.org/TR/, checked 2026-10-17)
  • MDN Web Docs, Learn web development: CSS styling basics and CSS layout, and the CSS reference (developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics, .../Core/CSS_layout, developer.mozilla.org/en-US/docs/Web/CSS, checked 2026-10-17)
  • W3C, CSS history and CSS1 Recommendation of 17 December 1996 (w3.org/Style/CSS20/history.html, w3.org/press-releases/1996/css1-rec, checked 2026-10-17)
  • W3C WCAG 2.2, success criteria 1.4.3 Contrast (Minimum)
  • 1.4.8 Visual Presentation, 1.4.10 Reflow, 1.4.12 Text Spacing (w3.org/TR/WCAG22/, checked 2026-10-17).

Checked: 2026-10-17