Loading

T2 CSS · Lesson 8

Responsive design

One page for every screen: the viewport meta tag; media queries with min-width, max-width, and, commas, ranges, print and orientation; building mobile first; fluid sizes with %, vw, max-width, clamp(), min() and max(); and images that fit, with the right file for each screen.

  • explain responsive design, and add the viewport meta tag that makes phones use their real width
  • write media queries with min-width, max-width, and, commas, the range form, print and orientation
  • build a page mobile first, with min-width queries in rising order and breakpoints chosen by the content
  • make sizes fluid with %, vw, max-width with auto margins, clamp(), min() and max()
  • make images fit any screen, and let the browser choose the right file with srcset and picture
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

Visitors reach a page on screens from a phone 360 pixels wide to an office screen 1920 pixels wide. Building a separate page for each would never end. Responsive design builds one page that reshapes itself, the way one kurta pattern is cut in every size.

These pages start with the viewport meta tag, the one line every responsive page needs. They show media queries, the habit of building for small screens first, and sizes that stretch between limits. They end with pictures that fit any screen and download at the right size.

Before you start

The story: The board on a hand-glass

The warden comes back from the gate with a glass no bigger than her palm. "Most visitors carry one of these," she says, "and the Fair's board looks dreadful on it." On the small glass, the board's three columns are squeezed into thin strips. The words break after every second letter, and the map of the Fair sticks out past the edge.

Corin wants to build a second, smaller board for the hand-glasses. Meher shakes her head. "Then you will keep two boards, and soon three, for every size of glass there is," she says. "Write one board that reads the size of the glass it is shown on, and reshapes itself to fit."

Every page so far was checked in one window, 800 pixels wide. Real visitors arrive on phones 360 pixels wide, on tablets, on laptops and on wide office screens. A page that reshapes itself to fit each one is called responsive. This lesson shows how: the tag that tells a phone its real width, the rules that apply only on some screens, and sizes that stretch and shrink between limits. It builds on these ideas; each has a tiny example.

What you already knowA tiny exampleWhere it comes back
The head holds facts about the page.<meta charset="utf-8"> in the head.One more meta tag tells a phone how wide to draw the page.
The viewport is the visible window.100vw is its width; a fixed box is pinned to it.Responsive rules read the viewport's width.
Relative units.50% of the parent; 2rem is twice the root font size.Sizes that follow the screen instead of staying fixed.
max-width caps a box.max-width: 600px stops a box growing past 600.A readable column on a wide screen, and an image that never spills.
Later rules win a tie.Two rules for p of equal weight: the later one applies.The order of responsive rules decides which wins.
Flex items can wrap.flex-wrap: wrap moves items to a new row.A layout that reflows by itself, with no rules for sizes.
A grid can fit as many columns as it can.repeat(auto-fill, minmax(150px, 1fr)).Another layout that adapts with no extra rules.
Images have a width and a height.<img width="600" height="400">.An image must shrink to fit a narrow screen.
DevTools can show a page as a phone would.The device toolbar in Chrome's DevTools.Testing a page at many widths without many devices.
Measuring what was drawn.getBoundingClientRect().Every block checks the layout at more than one window width.

By the end of this lesson you will be able to:

  • explain what responsive design is, and add the viewport meta tag that makes phones draw a page at their real width;
  • write media queries that apply rules only on some screens, with min-width, max-width, and, commas and media types;
  • build a page mobile first: a simple layout for small screens, enriched step by step for larger ones;
  • make sizes fluid with percentages, vw, max-width, clamp(), min() and max();
  • make images fit any screen, and let the browser pick the right file for each screen with srcset and picture.

How this lesson checks itself

Each layout below was rendered in Chrome at more than one window width, from a 375 pixel phone to a 1200 pixel desktop, and each check says which width it measured. One kind of window is a true phone's, which obeys the viewport meta tag as a real phone does.

In one line

A responsive page reshapes itself to the screen it is shown on; you need the viewport, relative units, max-width and the order in which rules win.

One page for every screen: the viewport meta tag

At a glance

A tailor sews one kurta pattern in many sizes, so that it fits every customer. A website faces the same problem: its visitors arrive with screens from a phone 360 pixels wide to an office screen 1920 pixels wide. Responsive design builds one page that reshapes itself to fit each of them.

It starts with one line in the head, the viewport meta tag. Without it, a phone pretends to be about 980 pixels wide and shrinks the whole page to fit, so the text becomes tiny. With it, the phone lays the page out at its real width.

Take a guess: Without the viewport meta tag, how wide does a phone pretend its screen is when it lays out a page?

A tailor in Surat sews one kurta pattern in many sizes, from small to extra large, so that it fits each customer. A website has the same problem in a different form: its visitors arrive with screens of every size, from a phone 360 pixels wide to an office screen 1920 pixels wide. Building a separate page for each size would never end.

responsive design

Building one page that reshapes itself to fit the screen it is shown on: columns that fold into one on a phone, text that stays readable, pictures that never spill over the edge.

The first step is not CSS at all. It is one line in the head of the page, and without it nothing else in this lesson works on a real phone.

Why phones pretend to be wide

When phones first got web browsers, almost every page was built for desktop screens about a thousand pixels wide. A phone that drew those pages at its real width would have broken them. So phones pretended: they laid the page out about 980 pixels wide, as a desktop would, then shrank the whole picture to fit the small screen. The page looked complete, but its text was too small to read without zooming.

Phones still do that today, for any page that does not say otherwise. The block below has no viewport tag. Its check runs in the kit's phone window, a true phone's screen 375 pixels wide.

<!DOCTYPE html>
<style>
  body { margin: 0; font-size: 16px; }
</style>
<h1>Asha Stores</h1>
<p>Fresh vegetables, delivered in Pune.</p>

Checked in Chrome

  • (the slip: with no viewport tag, the phone lays the page out 980 pixels wide and shrinks it, so the 16px text looks about 6px)

The phone's screen is 375 pixels wide, but the page was laid out 980 wide. To fit, everything is shrunk to about 375 ÷ 980, roughly two fifths of its size. A 16 pixel letter ends up looking about 6 pixels tall.

The viewport meta tag

The fix is a viewport meta tag in the head: a line that tells the phone to lay the page out at its own real width, and not to shrink it.

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; font-size: 16px; }
</style>
<h1>Asha Stores</h1>
<p>Fresh vegetables, delivered in Pune.</p>

Checked in Chrome

  • with the tag, the phone lays the page out at its real width, 375 pixels
  • on the phone: so the paragraph is 375 wide, and its 16px text is drawn at 16px

Read the tag aloud, piece by piece:

PieceRead it asWhat it does
name="viewport"this tag is about the viewportthe viewport is the area the page is drawn in
width=device-widththe width is the device's own widthlay the page out as wide as the screen really is, 375 on this phone
initial-scale=1start at a zoom of 1, full sizedo not shrink the page when it first opens

A memory aid

Every page's head gets the same line: <meta name="viewport" content="width=device-width, initial-scale=1">. Write it next to <meta charset="utf-8"> in every page you make, and forget about it.

CSS pixels and the dots on the screen

You may wonder how a phone that is 375 pixels wide can show sharp photos. The answer is that a CSS pixel is not one dot of the screen. Most phones pack two or three tiny dots into each CSS pixel, so the 375 pixel phone has 750 or more real dots across. The number of dots in each CSS pixel is the device pixel ratio.

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
</style>
<p>How sharp is this screen?</p>

Checked in Chrome

  • this phone has 2 dots in each CSS pixel
  • on the phone: so its 375 CSS pixels are 750 real dots across

For your CSS, this changes nothing: you always write CSS pixels, and the phone turns them into dots. It matters for pictures, as the images section will show: a sharp photo on this phone needs twice as many dots as its CSS width.

Switching off zoom

Some pages add user-scalable=no or maximum-scale=1 to the tag. That stops visitors from zooming in, and people with weak eyesight need to zoom to read. Never add them; the plain tag above is all a page needs.

Worked example 1

A school puts its exam results online. On a phone, the results table appears tiny, and parents must pinch and zoom to read their child's marks. The page's head has only its title and its charset. What is missing, and what does the phone do after the fix?

What we have: a page that looks shrunk on phones; a head with no viewport tag

What we need: the missing line, and the width the phone then lays the page out at

The plan: add the viewport meta tag to the head; the phone then uses its real width instead of pretending to be 980 wide

  1. Without the tag, the phone lays the page out 980 pixels wide and shrinks it to fit its screen.
  2. With the tag, it lays the page out at its own width, so 16px text is drawn at 16px.
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Class 10 results</title>
<style>
  body { margin: 0; }
</style>
<h1>Class 10 results</h1>
<p>Roll number 1042: 87%</p>

Checked in Chrome

  • the phone now lays the page out at its real width, 375

Add <meta name="viewport" content="width=device-width, initial-scale=1"> to the head. The phone then lays the page out at 375 pixels, its real width, and the marks are readable without zooming.

Check: in the phone's window, the page's width read 375, not 980.

When you are stuck: the viewport tag

Everything tiny on a phone, though the CSS looks right: the viewport meta tag is missing from the head.

Still tiny after adding it: check its spelling, letter by letter: name="viewport", width=device-width, initial-scale=1.

Fine in a desktop browser, wrong on a phone: desktop browsers ignore the tag, so test in DevTools' device toolbar or on a phone.

Your turn

Without a viewport tag, about how wide does a phone lay a page out?Tap to reveal
  1. Wide enough for the desktop pages of the past.

About 980 pixels, then it shrinks the page to fit.

What does width=device-width tell the phone?Tap to reveal
  1. Whose width?

To lay the page out at the screen's own width.

A phone has a device pixel ratio of 3 and is 360 CSS pixels wide. How many real dots across?Tap to reveal
  1. Multiply.

360 × 3 = 1080 dots.

Did you know?

The article that named responsive design

The name responsive web design comes from one article. Ethan Marcotte published Responsive Web Design in the magazine A List Apart on 25 May 2010. In it he wrote that we need to practise responsive web design, and he named its three technical ingredients: fluid grids, flexible images and media queries.

Why it fits here: This whole lesson follows his three ingredients: fluid sizes, pictures that fit, and media queries.

Source: A List Apart: Responsive Web Design, by Ethan Marcotte

Why phones pretended to be 980 pixels wide

Apple's guide to Safari on iOS explains the 980 pixels in this topic. It says Safari sets the viewport to reasonable defaults that work well for most web pages, and that the default width is 980 pixels. The same guide says a page uses the viewport meta tag to set the viewport's width and initial scale instead.

Why it fits here: It is the default that this topic's viewport meta tag switches off.

Source: Apple: Safari Web Content Guide, Configuring the Viewport

In one line

A responsive page fits every screen; it starts with the viewport meta tag, which makes a phone lay the page out at its real width instead of pretending to be 980 pixels wide.

Rules for some screens: media queries

At a glance

A tea stall's board says: ginger tea, 15 rupees; in winter, with honey. The second rule holds only when a condition is true. A media query does the same for screens: @media (condition) { rules } applies its rules only while the condition holds.

The condition min-width means from that width up, and max-width means from that width down. The word and joins two conditions, and a comma means or. Rules inside @media print apply only on paper, and orientation tells a tall screen from a wide one.

Take a guess: If a rule sits inside @media (min-width: 600px), does it apply on a phone 400 pixels wide?

A tea stall in Kolkata has a board: "Ginger tea, ₹15. In winter: with honey." The second rule holds only when a condition is true. CSS has the same thing for screens: a block of rules that applies only when the screen meets a condition, such as being at least 600 pixels wide.

media query

A condition about the screen, written @media (condition) { rules }. The rules inside apply only while the condition is true, and stop the moment it is false, for example when a window is made narrower.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  h1 { font-size: 24px; }
  @media (min-width: 600px) {
    h1 { font-size: 36px; }
  }
</style>
<h1>Asha Stores</h1>

Checked in Chrome

  • in the 800 pixel window, 800 is at least 600, so the heading is 36px
  • at 375 pixels, the condition is false, so the heading keeps 24px

Read @media (min-width: 600px) aloud as: "for screens whose width is at least 600 pixels". The rule outside the query is for everyone; the rule inside is added on top for the wider screens, and wins there because it comes later.

min-width and max-width

ConditionRead it asTrue at 375?True at 600?True at 800?
(min-width: 600px)600 or widernoyesyes
(max-width: 600px)600 or narroweryesyesno

Both words describe the screen, not the box: min-width here means the smallest screen width the rules are for. Notice that both include 600 itself. That detail comes back in the mistakes section.

A memory aid

min-width: from here up. max-width: from here down.

Joining conditions: and, and the comma

The word and joins two conditions that must both be true. It makes a range of widths, such as tablets from 480 to 900 pixels.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .tip { display: none; }
  @media (min-width: 480px) and (max-width: 900px) {
    .tip { display: block; }
  }
</style>
<p class="tip">Tip: turn your tablet sideways for the full menu.</p>

Checked in Chrome

  • at 800, inside the range, the tip shows
  • at 375, below the range, it is hidden
  • at 1024, above the range, it is hidden

A comma between conditions means or: the rules apply when any one of them is true.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .note { color: black; }
  @media (max-width: 400px), (min-width: 1000px) {
    .note { color: firebrick; }
  }
</style>
<p class="note">Delivery is free above ₹499.</p>

Checked in Chrome

  • at 800, neither is true: black
  • at 375, the first is true: firebrick
  • at 1024, the second is true: firebrick

The range form

Newer browsers, which means every current one, also accept conditions written like the comparisons of arithmetic. (width >= 600px) is the same as (min-width: 600px), and a range can be written in one go.

Older formRange formRead it as
(min-width: 600px)(width >= 600px)width at least 600
(max-width: 599px)(width < 600px)width below 600
(min-width: 480px) and (max-width: 900px)(480px <= width <= 900px)width from 480 to 900
<!DOCTYPE html>
<style>
  body { margin: 0; }
  h1 { font-size: 24px; }
  @media (width >= 600px) {
    h1 { font-size: 36px; }
  }
</style>
<h1>Asha Stores</h1>

Checked in Chrome

  • at 800, width >= 600 is true
  • at exactly 600, it is true too: >= includes 600
  • at 375, false

Media types: screen and print

A query can also name the kind of output. screen is any screen; print is the page when it is printed, or saved as a PDF; all is every kind, and is what a query means when it names none. You will often see @media only screen and (...). The word only was added long ago to make very old browsers skip the rule; today it changes nothing, so you may leave it out.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  @media print {
    nav { display: none; }
  }
</style>
<nav>Home | Offers | Cart</nav>
<p>Your bill: ₹1250</p>

Checked in Chrome

  • on screen the print rule does nothing: the menu shows
  • because this is a screen, not a printer

When the bill is printed, the menu is hidden, because a printed menu cannot be clicked. Print rules are a quiet kindness to anyone who prints a ticket, a receipt or a recipe.

Orientation

(orientation: landscape) is true when the window is wider than it is tall, as a phone turned on its side; (orientation: portrait) when it is taller than wide, or square.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .turn { display: none; }
  @media (orientation: portrait) {
    .turn { display: block; }
  }
</style>
<p class="turn">Turn your phone sideways to see the whole chart.</p>

Checked in Chrome

  • the 800 by 600 window is landscape: the hint is hidden
  • 375 by 600 is portrait: the hint shows

Worked example 2

A cinema's page shows a long tagline, "Mumbai's oldest single screen, since 1933", under its name. On phones it wraps onto three lines and pushes the show times down. Show the tagline only on screens 600 pixels and wider.

What we have: a tagline that should appear only on wider screens

What we need: a rule that hides it, and a query that brings it back from 600 up

The plan: hide it for everyone first, then show it inside (min-width: 600px)

  1. Outside any query: .tagline { display: none; }, for every screen.
  2. Inside @media (min-width: 600px): .tagline { display: block; }, which comes later and so wins on wide screens.
<!DOCTYPE html>
<style>
  body { margin: 0; }
  .tagline { display: none; }
  @media (min-width: 600px) {
    .tagline { display: block; }
  }
</style>
<h1>Regal Talkies</h1>
<p class="tagline">Mumbai's oldest single screen, since 1933</p>
<p>Shows: 12:30, 4:00, 9:15</p>

Checked in Chrome

  • at 800, the tagline shows
  • at 375, it is hidden, and the show times move up
  • at exactly 600, it shows

.tagline { display: none; } @media (min-width: 600px) { .tagline { display: block; } }

Check: the browser hid the tagline at 375 and showed it at 600 and 800.

When you are stuck: media queries

A query that never applies: check the brackets around the condition, and the colon: (min-width: 600px).

A query that applies on the wrong screens: say min-width aloud as "from here up" and max-width as "from here down".

A rule inside a query that loses: a rule outside it, later in the sheet, beats it in a tie; put queries after the rules they change.

Your turn

Is (max-width: 600px) true on a screen 600 pixels wide?Tap to reveal
  1. Does "600 or narrower" include 600?

Yes: both min-width and max-width include the number itself.

What does a comma between two conditions mean?Tap to reveal
  1. Must both be true?

Or: any one true is enough.

Write (min-width: 768px) in the range form.Tap to reveal
  1. Width at least 768.

(width >= 768px).

Did you know?

A media type for phones, now deprecated

CSS2, in 1998, already had a media type for phones: handheld, meant for small screens, often monochrome, with limited bandwidth. Media Queries Level 4 now lists handheld among the deprecated media types that authors must not use. It even expects every media type to be deprecated in time, as media features such as width capture the differences better.

Why it fits here: It is why this topic asks about width, with min-width and max-width, instead of naming a kind of device.

Sources: W3C: CSS level 2 (1998); W3C: CSS level 2, Media types (1998); W3C: Media Queries Level 4

Dark mode is a media query

Dark mode is a media query too. Media Queries Level 5 defines prefers-color-scheme, with the values light and dark, which reflects the user's wish for a light or a dark colour theme. So @media (prefers-color-scheme: dark) holds the rules for readers who have chosen dark mode on their device.

Why it fits here: It is this topic's @media, asking about the reader's choice instead of the screen's width.

Source: W3C: Media Queries Level 5

In one line

@media (condition) { rules } applies its rules only while the condition holds: min-width means from here up, max-width from here down, and joins two conditions, a comma means or, and print rules apply only on paper.

Small screens first: mobile-first design

At a glance

Packing for a trip, you first pack what you need every day, then add extras for special days. Mobile-first design builds a page the same way. The base rules, outside any query, are for the smallest screen, usually one column.

Then min-width queries, in rising order, enrich the layout as the screen grows. Breakpoints go where the content needs them, not at the widths of particular phones. Best of all are layouts that adapt with no query at all, such as a grid of cards that fits as many as the screen holds.

Take a guess: In a mobile-first style sheet, should the media queries use min-width or max-width?

Packing for a trip, you first pack what you need on every day of it: clothes, a toothbrush, a charger. Only then do you add the extras for special days, such as a jacket for the hills. Mobile-first design builds a page the same way: first the plain layout every screen can show, usually one column, then extra rules that enrich it on wider screens.

mobile first

Writing the base rules, outside any query, for the smallest screen, then adding min-width queries, in rising order, that change the layout as screens get wider.

Four cards: one column, then two, then four

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .shop { display: grid; grid-template-columns: 1fr; }
  @media (min-width: 600px) {
    .shop { grid-template-columns: 1fr 1fr; }
  }
  @media (min-width: 900px) {
    .shop { grid-template-columns: repeat(4, 1fr); }
  }
  .shop div { height: 60px; }
</style>
<div class="shop">
  <div>Rice</div>
  <div>Dal</div>
  <div>Atta</div>
  <div>Ghee</div>
</div>

Checked in Chrome

  • at 800: two columns of 400, from the 600 query
  • at 375: no query is true, so the base gives one column
  • at 700: two columns of 350
  • at 1024: both queries are true, and the later one, four columns, wins

Follow it width by width. At 375, neither query is true, so the base rule alone gives one column. At 700, the first query is true: two columns. At 1024, both queries are true, and they set the same property, so the later one wins: four columns. That is why mobile-first queries go in rising order: each wider step comes later and overrides the step before it.

Why start small?

ReasonWhat it means
Most visitors are on phonesIn India most people go online on a phone, so the base layout is the one most people see.
The simple layout is the safe oneOne column fits every screen; an old or unusual browser that skips queries still gets a page that works.
Small screens force choicesStarting with little room makes you decide what matters most, and that order usually suits wide screens too.
Less to undoAdding columns as room grows is easier than squeezing a wide layout and undoing its pieces one by one.

The other way round is called desktop first: the base is the wide layout, and max-width queries, in falling order, simplify it for smaller screens. Both work; mobile first is the usual choice today, and this lesson uses it.

Mobile firstDesktop first
the base rules are forthe smallest screenthe widest screen
the queries usemin-width, from here upmax-width, from here down
the queries go inrising order: 600, then 900falling order: 900, then 600

A memory aid

Mobile first: small base, min-width up. Base rules first, then each wider screen's query after it.

Where to put the breakpoints

A width where a query changes the layout is called a breakpoint. It is tempting to choose breakpoints from the sizes of popular phones and tablets, but new devices appear every year. Choose them from the content instead: start with the window narrow, widen it slowly, and add a breakpoint at the width where the layout starts to look stretched or empty. Round numbers such as 600, 900 and 1200 are common starting points.

Watching the breakpoints

In Chrome's DevTools, the device toolbar shows the page at any width you type, and a bar above it marks the widths where the page's queries change.

Layouts that adapt with no query

Some layouts from the flexbox and grid lessons are responsive already, with no media query at all. A grid that fits as many columns of at least 150 pixels as it can changes its number of columns by itself.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
  .cards div { height: 60px; }
</style>
<div class="cards">
  <div>1</div><div>2</div><div>3</div><div>4</div>
  <div>5</div><div>6</div><div>7</div><div>8</div>
</div>

Checked in Chrome

  • at 800: five columns of 160
  • at 360: two columns of 180
  • at 1200: all eight cards fit on one row of 150 each

Prefer such layouts where they fit: they adapt to every width, not just at the breakpoints you chose. Media queries are for the changes they cannot make, such as moving a sidebar below the main text.

Worked example 3

A school's site has four menu links. On phones they should stack, one under another, each the full width, easy to tap. From 600 pixels up they should sit in a row. Write it mobile first.

What we have: four links in a nav; a stacked layout for phones, a row for wider screens

What we need: the base rule for phones, and one query for wider screens

The plan: a flex container with flex-direction: column as the base, and flex-direction: row inside (min-width: 600px)

  1. Base, for every screen: nav { display: flex; flex-direction: column; }. The links stack, and as flex items in a column they stretch to the full width.
  2. From 600 up: nav { flex-direction: row; } inside the query. It comes later, so it wins on wider screens, and the links sit side by side.
<!DOCTYPE html>
<style>
  body { margin: 0; }
  nav { display: flex; flex-direction: column; }
  nav a { padding: 12px; }
  @media (min-width: 600px) {
    nav { flex-direction: row; }
  }
</style>
<nav>
  <a href="#home">Home</a>
  <a href="#notices">Notices</a>
  <a href="#results">Results</a>
  <a href="#contact">Contact</a>
</nav>

Checked in Chrome

  • at 800, all four links share the top row
  • at 360, all four start at the left edge, one under another
  • and each is the full 360 wide, easy to tap

nav { display: flex; flex-direction: column; } @media (min-width: 600px) { nav { flex-direction: row; } }

Check: the links stacked at 360 and shared one row at 800.

Worked example 4

A news site's article page has the article and a "Most read" list. On phones the list should come under the article, the full width. From 900 pixels up it should sit beside the article in a 300 pixel sidebar. Write it mobile first and say where the list lands at 375 and at 1024.

What we have: an article and an aside; one column on phones, two from 900

What we need: a grid whose columns change at 900, and the list's place at two widths

The plan: a grid of one column as the base, so the aside follows the article; inside (min-width: 900px), columns of 1fr and 300px

  1. At 375: one column, so the aside starts where the article ends, at the left edge, 375 wide.
  2. At 1024: the columns are 1fr and 300px, so the article takes 1024 − 300 = 724, and the aside starts at 724, on the same row.
<!DOCTYPE html>
<style>
  body { margin: 0; }
  .page { display: grid; grid-template-columns: 1fr; }
  article { height: 400px; }
  @media (min-width: 900px) {
    .page { grid-template-columns: 1fr 300px; }
  }
</style>
<div class="page">
  <article>Monsoon reaches Kerala early this year...</article>
  <aside>Most read</aside>
</div>

Checked in Chrome

  • at 800, below 900: the list comes under the article, at 400
  • at 375: under the article, the full 375 wide
  • at 1024: beside the article, at 724, 300 wide

.page { display: grid; grid-template-columns: 1fr; } @media (min-width: 900px) { .page { grid-template-columns: 1fr 300px; } }: under the article at 375; beside it at 724 from 900 up.

Check: the browser put the list at 0, 400 on the phone width and at 724, 0 at 1024.

When you are stuck: mobile-first layouts

A wider query that never wins: is it written after the narrower one? Rising order: 600, then 900.

Not sure where a breakpoint belongs: widen the window slowly and watch for the width where the layout looks wrong.

Writing many queries for a card grid: try repeat(auto-fill, minmax(...)) first; it needs none.

Your turn

In mobile-first CSS, which rules come first: those for phones or those for wide screens?Tap to reveal
  1. Small base.

Those for phones, outside any query.

At 1024 pixels, both (min-width: 600px) and (min-width: 900px) are true, and both set the columns. Which wins?Tap to reveal
  1. Equal weight.

The one that comes later, which in rising order is the 900 query.

How should a breakpoint be chosen?Tap to reveal
  1. Devices change every year.

From the content: where the layout starts to look wrong.

Did you know?

Mobile first began as a blog post

A short blog post of 2009 argued for mobile first. On 3 November 2009 the designer Luke Wroblewski wrote that, more often than not, the mobile version of a site was designed and built after the PC version was complete. He then gave three reasons to design for mobile first instead, the first being that mobile was exploding.

Why it fits here: This topic's order, small screens first and then wider ones, is the order he argued for.

Source: LukeW: Mobile First, by Luke Wroblewski

Phones overtook computers in 2016

Designing for phones first matches how people browse. The analytics company StatCounter reported on 1 November 2016 that, worldwide, internet use on mobiles and tablets had exceeded desktop use for the first time that October: 51.3% against 48.7%. In other words, a little more than half of the world's web use that month came from phones and tablets.

Why it fits here: It is one reason this topic's base rules are written for the smallest screen.

Source: StatCounter: Mobile and tablet internet usage exceeds desktop for first time worldwide

In one line

Mobile first means base rules for the smallest screen, then min-width queries in rising order that enrich the layout; choose breakpoints where the content needs them, and prefer layouts that adapt with no query.

Sizes that stretch: fluid widths and clamp()

At a glance

A rubber band stretches around a small bundle of pencils or a large one, but within limits. Good responsive sizes behave like that band. A width in % is a share of the parent's width, and vw is a share of the window's width.

A max-width with auto margins, or min(), makes a column that stays readable on wide screens. For text, clamp(smallest, wanted, largest) gives a size that grows with the screen but never leaves its bounds. For example, clamp(1rem, 4vw, 2rem) stays between 1rem and 2rem.

Take a guess: If a heading has font-size: clamp(1rem, 4vw, 2rem), how big is it on a screen where 4vw is 3rem?

A rubber band stretches to fit around a small bundle of pencils or a large one, but it has limits: too small a bundle and it slips off, too large and it snaps. Good responsive sizes behave like that band: they stretch with the screen, between a smallest and a largest size that you choose. Sizes like these are called fluid.

Percentages: a share of the parent

A width in % is a share of the parent's width, so it grows and shrinks with it. width: 50% is 400 pixels in an 800 pixel page and 187.5 on a 375 pixel phone. You met percentages in the colours and units lesson; here they do their real job.

A readable column: max-width and auto margins

Lines of text that run across a whole wide screen are tiring to read: the eye loses its place on the way back to the start of the next line. A column of text reads best at about 60 to 75 letters a line. The usual answer is a column that fills a phone but stops growing on wide screens, sitting in the middle.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  main { max-width: 600px; margin: 0 auto; }
</style>
<main>
  <h1>How to store rice</h1>
  <p>Keep it in a dry, airtight tin, away from sunlight.</p>
</main>

Checked in Chrome

  • at 800: the column stops at 600, centred: (800 − 600) ÷ 2 = 100 on each side
  • at 375: the column fills the phone
  • at 1024: still 600, centred at 212

Two rules do it. max-width: 600px lets the column be as wide as its parent, up to 600 and no more. margin: 0 auto shares any space left over equally between the two sides, as you saw in the box model lesson.

vw: a share of the window

The unit vw means one hundredth of the window's width: 5vw is 5% of it, 40 pixels in an 800 pixel window and 18.75 on a 375 pixel phone. Unlike %, it ignores the parent and looks only at the window.

Text sized in vw alone

A heading of font-size: 5vw is a tiny 18.75 pixels on a phone and a huge 96 pixels on a 1920 pixel screen. Worse, it stays the same size when a reader zooms in to read it, because zooming makes the window narrower in CSS pixels. Text needs limits, and a part that follows the reader's own font size.

clamp(): a size with limits

clamp() takes three values: the smallest size, the size it would like, and the largest size. Read clamp(24px, 5vw, 40px) as: "5vw, but never less than 24 pixels and never more than 40".

<!DOCTYPE html>
<style>
  body { margin: 0; }
  h1 { font-size: clamp(24px, 5vw, 40px); }
</style>
<h1>Diwali offers</h1>

Checked in Chrome

  • at 800: 5vw is 40, inside the limits: 40px
  • at 375: 5vw is 18.75, below the smallest, so 24px
  • at 600: 5vw is 30, inside the limits: 30px
  • at 1024: 5vw is 51.2, above the largest, so 40px
Window5vwclamp(24px, 5vw, 40px)Why
37518.7524pxbelow 24, so the smallest
6003030pxbetween the limits, so 5vw itself
8004040pxexactly the largest
102451.240pxabove 40, so the largest

A memory aid

clamp(smallest, wanted, largest). The wanted size in the middle, held between its two limits, like a rubber band between two pegs.

For text, write the limits in rem and add a rem part to the wanted size, such as clamp(1.5rem, 1rem + 2vw, 2.5rem). Then the heading still grows when a reader sets a larger font size in the browser, and it never shrinks below one and a half times the reader's own text size.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  h1 { font-size: clamp(1.5rem, 1rem + 2vw, 2.5rem); }
</style>
<h1>Diwali offers</h1>

Checked in Chrome

  • at 800: 16 + 16 = 32px
  • at 375: 16 + 7.5 = 23.5, below 1.5rem, so 24px
  • at 600: 16 + 12 = 28px
  • at 1200: 16 + 24 = 40px, exactly 2.5rem

min() and max()

min() picks the smallest of its values, and max() the largest. width: min(100%, 600px) is the readable column again in one rule: the full width, or 600, whichever is smaller. padding: max(16px, 4vw) grows with the window, but never below 16 pixels.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  main { width: min(100%, 600px); margin: 0 auto; padding: 0 max(16px, 4vw); box-sizing: border-box; }
</style>
<main><p>Keep rice in a dry, airtight tin.</p></main>

Checked in Chrome

  • at 800: the column is 600 wide, and 4vw is 32, so the padding is 32px
  • at 375: the full width, and 4vw is 15, below 16, so the padding is 16px
FunctionGivesRead it asA use
min(a, b)the smallerat mostwidth: min(100%, 600px)
max(a, b)the largerat leastpadding: max(16px, 4vw)
clamp(a, b, c)b, held between a and cat least a, at most cfont-size: clamp(1.5rem, 1rem + 2vw, 2.5rem)

min means at most

It feels backwards at first: min() sets a largest size, because it picks the smaller value. Read min(100%, 600px) as "at most 600", and max(16px, 4vw) as "at least 16".

Worked example 5

A festival sale page has a big heading. It should be 28 pixels on small phones and grow with the window, but never pass 48 pixels. The designer suggests 4vw + 12px as the wanted size. Write the rule and work out its size at 375, 600, 800 and 1200.

What we have: the smallest size 28, the largest 48, the wanted size 4vw + 12px

What we need: one font-size rule, and its size at four widths

The plan: clamp(28px, 4vw + 12px, 48px); work out 4vw + 12 at each width, then hold it between 28 and 48

  1. At 375: 4vw is 15, plus 12 is 27, below 28, so 28.
  2. At 600: 24 + 12 = 36, between the limits, so 36.
  3. At 800: 32 + 12 = 44, so 44.
  4. At 1200: 48 + 12 = 60, above 48, so 48.
<!DOCTYPE html>
<style>
  body { margin: 0; }
  h1 { font-size: clamp(28px, 4vw + 12px, 48px); }
</style>
<h1>Navratri sale</h1>

Checked in Chrome

  • at 800: 44px
  • at 375: 28px, the smallest
  • at 600: 36px
  • at 1200: 48px, the largest

h1 { font-size: clamp(28px, 4vw + 12px, 48px); }: 28, 36, 44 and 48 pixels at 375, 600, 800 and 1200.

Check: the browser measured exactly those four sizes.

When you are stuck: fluid sizes

Not sure which of min and max you need: say "at most" for min() and "at least" for max().

clamp() seems stuck at one size: the wanted value is always outside the limits; work it out at a few widths.

A column that touches the screen's edges on phones: give it padding as well, such as max(16px, 4vw).

Your turn

What is 10vw in a window 1200 pixels wide?Tap to reveal
  1. One hundredth, ten times.

120 pixels.

What size is clamp(20px, 3vw, 30px) at 400 pixels?Tap to reveal
  1. 3vw is 12.

12 is below 20, so 20px.

Which rule gives a column at most 700 pixels wide, in one function?Tap to reveal
  1. The smaller of two.

width: min(100%, 700px).

Did you know?

clamp() settles even an impossible request

clamp() settles even an impossible request. The CSS Values standard says it takes a minimum, a central value and a maximum, and gives the central value clamped between the other two. If the minimum is bigger than the maximum, the minimum wins. So clamp(1rem, 4vw, 2rem) never goes below 1rem or above 2rem.

Why it fits here: It is the exact rule behind this topic's clamp(smallest, wanted, largest).

Source: W3C: CSS Values and Units Level 4

100vw can be too wide

A width of 100vw can be too wide. The CSS Values standard sizes viewport units as if scrollbars did not exist. So on a computer that shows a vertical scrollbar, a box 100vw wide is wider than the space beside the scrollbar, and the page gains a sideways scroll. A width of 100% avoids it.

Why it fits here: It is a trap in this topic's vw: a share of the whole window, the scrollbar's strip included.

Source: W3C: CSS Values and Units Level 4

In one line

Fluid sizes stretch with the screen between limits: % follows the parent, vw the window; max-width with auto margins, or min(), makes a readable column, and clamp(smallest, wanted, largest) sizes text that grows but stays in bounds.

Pictures that fit: responsive images

At a glance

Text wraps to any width by itself, but a picture 600 pixels wide stays 600 pixels wide, even on a phone 375 pixels across. The fix is two rules, max-width: 100% and height: auto, so that the picture shrinks to fit and keeps its shape.

The rules object-fit: cover and background-size: cover fill a fixed box without stretching. The srcset attribute, with sizes, lets the browser download a file of the right size, and the picture element can choose a different crop for each screen.

Take a guess: If an image has max-width: 100% but a fixed height of 300px, what happens to its shape on a narrow phone?

A photo is the stubborn part of a responsive page. Text wraps to any width by itself, but an image 600 pixels wide stays 600 pixels wide, even on a phone 375 pixels across. The page then grows wider than the screen, and the visitor has to scroll sideways to see it.

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
</style>
<h1>Fresh tomatoes</h1>
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='400'%3E%3Crect width='600' height='400' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E" alt="A red tomato" width="600" height="400">

Checked in Chrome

  • (the slip: on the 375 pixel phone, the 600 pixel image makes the page 600 wide, so it scrolls sideways)

The fix: max-width: 100% and height: auto

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
  img { max-width: 100%; height: auto; }
</style>
<h1>Fresh tomatoes</h1>
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='400'%3E%3Crect width='600' height='400' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E" alt="A red tomato" width="600" height="400">

Checked in Chrome

  • in the 800 window, there is room: the image keeps its 600
  • on the phone, it shrinks to 375 by 250, the same shape
  • and the page is the phone's width again: no sideways scroll

Each rule has a job. max-width: 100% says the image may be as wide as its parent and no wider; it never stretches a small image bigger. height: auto lets the height follow the width, so the image keeps its shape: 600 by 400 becomes 375 by 250, because 375 ÷ 600 and 250 ÷ 400 are both 0.625.

max-width without height: auto

With only max-width: 100%, the height written in the HTML, 400, stays as it was while the width shrinks to 375. The photo is squashed sideways. Always write the two rules together, and keep the width and height attributes in the HTML: they let the browser keep the right space before the image arrives.

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
  img { max-width: 100%; }
</style>
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='400'%3E%3Crect width='600' height='400' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E" alt="A red tomato" width="600" height="400">

Checked in Chrome

  • on the phone: (the slip: 375 wide but still 400 tall, so the tomato is squashed)

Filling a box of a fixed shape: object-fit

Product cards often need every photo in the same shape, say 300 by 200, though the photos come in every shape. Forcing a width and a height squashes them. object-fit: cover fills the box and keeps the photo's shape, cutting off whatever spills over the edges, the way a photo frame hides the edges of a print.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .thumb { width: 300px; height: 200px; object-fit: cover; }
</style>
<img class="thumb" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400'%3E%3Crect width='400' height='400' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E" alt="A red tomato" width="400" height="400">

Checked in Chrome

  • the box is 300 by 200
  • and the square photo covers it, its top and bottom cut off, not squashed
object-fitWhat happens to the photo
fillthe default: stretched to the box's exact shape, so it may be squashed
coverfills the whole box, keeps its shape, and the edges that spill over are cut off
containfits entirely inside the box, keeps its shape, and leaves empty bands

Background images have the same choice through background-size. A banner with background-size: cover is always filled by its picture, whatever its width, and background-position: center keeps the middle of the picture in view.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .banner { height: 150px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='400'%3E%3Crect width='600' height='400' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E"); background-size: cover; background-position: center; }
</style>
<div class="banner"></div>

Checked in Chrome

  • the banner's picture covers it at every width

The right file for each screen: srcset and sizes

Shrinking a big photo fixes its size on the screen, but the phone still downloads the whole big file. On a slow connection, or a small data pack, that is a waste. The srcset attribute lists several files of the same photo at different widths, and lets the browser download only the one it needs.

On a real site

<img src="tomato-800.jpg" alt="A red tomato"
     srcset="tomato-400.jpg 400w, tomato-800.jpg 800w, tomato-1600.jpg 1600w"
     sizes="100vw">

Read it piece by piece. Each entry of srcset is a file and its true width: 400w means the file is 400 pixels wide. sizes tells the browser how wide the image will be drawn: 100vw, the whole window. The browser multiplies that width by the screen's device pixel ratio and picks the smallest file that is wide enough. src is kept for very old browsers.

ScreenDrawn widthDots neededFile the browser took
a laptop window, 800 wide, 1 dot per pixel800800tomato-800.jpg
a phone, 375 wide, 1 dot per pixel375375tomato-400.jpg
a phone, 375 wide, 2 dots per pixel375750tomato-800.jpg
a wide screen, 1200, 1 dot per pixel12001200tomato-1600.jpg

These are the choices Chrome made when the lesson's files were served to it at each width. The browser is allowed to choose differently, for example to keep using a bigger file it already has, which is why srcset offers choices rather than giving orders.

When the image is not drawn across the whole window, sizes can say so, with media conditions: sizes="(min-width: 900px) 33vw, 100vw" means "a third of the window on screens 900 and wider, otherwise the whole window". At 1200 pixels the picture is drawn about 400 wide, and Chrome took the 400 pixel file.

A different picture for each screen: picture

Sometimes a phone needs a different crop, not just a smaller file: a wide banner of a busy market becomes a jumble of tiny people on a narrow screen, where a close-up of one stall reads better. The <picture> element offers sources with media conditions; the browser takes the first whose condition is true, and falls back to the <img> inside.

On a real site

<picture>
  <source media="(min-width: 800px)" srcset="market-wide.jpg">
  <img src="market-stall.jpg" alt="A vegetable stall at Crawford Market">
</picture>

In Chrome, a window 800 or wider took the wide banner, and a 375 pixel window took the close-up. The alt text lives on the <img> and serves both pictures, so it must describe what both show.

Worked example 6

A recipe site shows a photo of a dish, 1200 by 800, at the top of each recipe. On phones it spills off the screen, and on wide screens it should never be drawn wider than 800. Write the CSS and say its size at 375 and at 1024.

What we have: an image 1200 by 800; phones spill; wide screens should stop at 800

What we need: rules that shrink it on phones, cap it at 800, and keep its shape

The plan: max-width: 100% for phones, a width of 800 for the cap, height: auto for the shape; or the shorter width: min(100%, 800px)

  1. At 375: min(100%, 800px) is 375; the height follows: 800 × 375 ÷ 1200 = 250.
  2. At 1024: the smaller of 1024 and 800 is 800; the height: 800 × 800 ÷ 1200 = 533.33, drawn about 533.
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
  .dish { width: min(100%, 800px); height: auto; }
</style>
<img class="dish" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1200' height='800'%3E%3Crect width='1200' height='800' fill='%23f4c430'/%3E%3Ccircle cx='300' cy='200' r='120' fill='%23c0392b'/%3E%3C/svg%3E" alt="A plate of masala dosa" width="1200" height="800">

Checked in Chrome

  • at 800, the dish is 800 wide
  • on the phone: 375 by 250
  • at 1024: capped at 800, and 533 tall

.dish { width: min(100%, 800px); height: auto; }: 375 by 250 on the phone, 800 by about 533 at 1024.

Check: the browser drew exactly those sizes.

When you are stuck: responsive images

A page that scrolls sideways on phones: look for an image, a table or a box with a fixed width wider than the screen.

A photo squashed or stretched: add height: auto, or use object-fit: cover for a box of fixed shape.

Not sure which file srcset chose: DevTools' Network panel lists each file the page downloaded, and img.currentSrc names it.

Your turn

Which two rules make an image shrink to fit its parent and keep its shape?Tap to reveal
  1. One for the width, one for the height.

max-width: 100% and height: auto.

In srcset, what does 800w after a file name mean?Tap to reveal
  1. A width, but of what?

The file is 800 pixels wide.

A phone 360 wide has 3 dots per pixel, and sizes is 100vw. How wide a file does it want?Tap to reveal
  1. Multiply.

360 × 3 = 1080 pixels, so it takes the smallest file at least that wide.

Did you know?

Width and height stop the page jumping

Write width and height on an image, and the page stops jumping as it loads. The HTML standard maps those two attributes to the CSS aspect-ratio property, so the browser can reserve a box of the right shape before the picture arrives. The web.dev advice on layout shift is to always include width and height on images and videos.

Why it fits here: This topic's height: auto keeps that reserved shape while the picture shrinks to fit.

Sources: WHATWG: HTML Standard, Rendering; web.dev: Optimize Cumulative Layout Shift

The browser picks the file

With srcset, the browser chooses which file to download, not the page. The HTML standard says it chooses depending on the screen's pixel density, the zoom level, and possibly whether a sharper image is already available. So two visitors to the same page can receive two different files.

Why it fits here: This topic's srcset offers the choices; the browser makes the choice.

Source: WHATWG: HTML Standard, Images

In one line

Images get max-width: 100% and height: auto so they shrink and keep their shape; object-fit and background-size: cover fill fixed boxes. The srcset attribute, with sizes, lets the browser download a file the right size, and picture chooses a different crop for each screen.

Where it is used

Every page built today is expected to be responsive. These are the pieces you will meet most.

What you learnedWhere it is usedA real example
the viewport meta tagthe head of every pagethe first lines of any news site's page
mobile-first media queriespage layoutsan online shop: one column of products on a phone, four on a laptop
layouts with no querycard grids and wrapping rowsa food delivery app's list of restaurants
max-width with auto marginsarticles and blogsa recipe's text in a calm column on a wide screen
clamp() for textheadings that grow with the screena festival sale page's big title
max-width: 100% on imagesevery image in an articlephotos in a travel blog
object-fit: coverproduct and profile picturesthe round photos of friends in a chat app
srcset and sizeslarge photos on busy sitesa news site sending phones smaller files
@media printtickets, bills and recipesa railway ticket page that prints without its menu

Mistakes and debugging

These are the responsive slips everyone makes, each measured in the browser.

1. No viewport tag

The CSS is perfect, and the phone shows a shrunken desktop page, because it lays the page out 980 pixels wide. The fix: the viewport meta tag in the head of every page.

2. A query written before the rule it changes

<!DOCTYPE html>
<style>
  body { margin: 0; }
  @media (max-width: 600px) {
    .g { grid-template-columns: 1fr; }
  }
  .g { display: grid; grid-template-columns: 1fr 1fr 1fr; }
</style>
<div class="g"><div>Rice</div><div>Dal</div><div>Atta</div></div>

Checked in Chrome

  • (the slip: at 375 the query is true, but the base rule comes later and wins the tie, so the phone still gets three thin columns)

A media query adds no weight to a rule. Inside or outside a query, two rules with equal selectors are decided by order. The fix: base rules first, queries after them.

3. Two queries that both hold at the breakpoint

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .g { display: grid; }
  @media (max-width: 600px) {
    .g { grid-template-columns: 1fr; }
    .note { font-size: 14px; }
  }
  @media (min-width: 600px) {
    .g { grid-template-columns: 1fr 1fr 1fr; }
  }
</style>
<div class="g"><div>Rice</div><div>Dal</div><div>Atta</div></div>
<p class="note">Prices include GST.</p>

Checked in Chrome

  • (the slip: at exactly 600 both queries are true, so the page gets the wide layout's three columns and the phone's small text, a mixture)

A desktop-first sheet with (max-width: 600px) and a mobile-first one with (min-width: 600px) overlap at 600 itself, and a 600 pixel window gets a mixture. The fix: pair (max-width: 599px) with (min-width: 600px), or use the range form, (width < 600px) and (width >= 600px), which cannot overlap.

4. A box with a fixed width

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
  .page { width: 1000px; }
</style>
<div class="page">Welcome to Asha Stores</div>

Checked in Chrome

  • (the slip: the 1000 pixel box makes the phone's page 1000 wide, so it scrolls sideways)

The fix: max-width: 1000px instead of width, or width: min(100%, 1000px). The same goes for tables, long words and long links: overflow-wrap: anywhere lets a long link break.

5. Hiding what phone users need

Hiding a whole section with display: none on small screens is quick, but phone visitors may need it most, such as a shop's phone number. The fix: rearrange and shorten, and hide only what truly does not matter on a small screen.

6. Images without their attributes

An image with no width and height in the HTML takes no space until it arrives, and then pushes the text down while the visitor reads. The fix: keep the width and height attributes, and let max-width: 100%; height: auto shrink it.

The debugging corner: test at every width

In Chrome's DevTools, the device toolbar (the phone and tablet button at the top left of DevTools) shows the page at any width and as a chosen phone, with its touch screen and its dots per pixel. Drag the width slowly from narrow to wide and watch for the moment something breaks. To find what makes a page scroll sideways, look for the element whose right edge is past the screen's in the Elements panel; and before trusting the result, open the page once on a real phone.

Quick card

The lesson on one card.

Every idea of the lesson

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { margin: 0; }
  main { max-width: 900px; margin: 0 auto; }
  h1 { font-size: clamp(1.5rem, 1rem + 2vw, 2.5rem); }
  .shop { display: grid; grid-template-columns: 1fr; }
  @media (min-width: 600px) {
    .shop { grid-template-columns: 1fr 1fr 1fr; }
  }
  img { max-width: 100%; height: auto; }
  @media print {
    nav { display: none; }
  }
</style>
<nav>Home | Offers</nav>
<main>
  <h1>Asha Stores</h1>
  <div class="shop"><div>Rice</div><div>Dal</div><div>Atta</div></div>
</main>

Checked in Chrome

  • at 800, from 600 up: three columns
  • the heading is 1rem + 2vw = 32px, inside its limits
  • on the phone, the viewport tag gives its real width, 375
  • on the phone: the base rule gives one column
  • on the phone: and the heading stops at its smallest, 1.5rem
  • at 1200, the main column stops at 900
  • at 1200 pixels wide: and the heading at its largest, 2.5rem
ToolWrite it asIt means
viewport tag<meta name="viewport" content="width=device-width, initial-scale=1">phones use their real width
media query@media (min-width: 600px) { }these rules from 600 up
and, comma(a) and (b), (a), (b)both, or either
range form(width >= 600px)the same as min-width: 600px
print@media print { }only on paper
readable columnmax-width: 600px; margin: 0 autoat most 600, centred
clampclamp(1.5rem, 1rem + 2vw, 2.5rem)grows, between limits
min and maxmin(100%, 600px), max(16px, 4vw)at most, at least
imagesmax-width: 100%; height: autoshrink to fit, keep the shape
object-fitobject-fit: coverfill a fixed box, crop the edges
srcsetsrcset="a-400.jpg 400w, a-800.jpg 800w"the browser picks a file the right size

And the order to build in: the viewport tag, a base for the smallest screen, min-width queries rising, fluid sizes between limits, and images that fit.

The story: One board, every glass

On the hand-glass, the columns now fold into one, stall under stall, and the map shrinks to fit its width. On the great wall glass by the gate, the same board opens out into three columns again.

The heading grows with the glass, but never past a size you chose, and never below one. Corin turns the hand-glass on its side, and the board rearranges itself while he watches.

"One board," Meher says, "and it fits every glass, including glasses nobody has made yet."

Reagents gathered: @media, min-width, viewport, max-width, clamp, srcset.

Sources

  • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
  • HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)