{module 4}
A page that fits a phone
Making it look right with CSS20 min read
What you will be able to do
- Write the styles for a phone first, and add one media query that uses the room of a wide screen.
- Make an image shrink to fit a small screen without changing its shape.
- Test a page at a width of 390 pixels, and find what makes it scroll sideways.
Why it matters
Himalaya Trek Hire rents trekking gear in Pokhara, Nepal, to walkers who are about to start a trek. Anil Gurung, the owner, built his page on a laptop. Most of his customers open it on a phone, often on a slow connection in a guesthouse.
On a phone, the photo at the top was wider than the screen. The page could be dragged sideways, and every line of text was cut off at the right edge. The three items of gear sat in a row, each too narrow to read. Several walkers sent messages to ask for the prices, which were on the page all along.
A page has to work on the smallest screen first. This lesson shows how to write it that way, and then how to use the extra room when there is some.
The idea
The viewport line
In module 2 you put this line in the head of every page:
<meta name="viewport" content="width=device-width, initial-scale=1" />Here is why. The viewport is the area of the screen the page is drawn in. Without this line, a phone's browser pretends to be about 980 pixels wide, lays the page out at that width, and shrinks the result to fit. The text becomes tiny. With the line, the page is laid out at the real width of the phone. Nothing in this lesson works without it.
The small screen first
A phone is narrow, so a phone layout is one column, with the parts in the order of the HTML. That is normal flow, which needs almost no CSS. A wide layout needs more: a centred column, things side by side.
So write the rules for a phone first, outside any condition. Then add the extra rules for a wide screen. This is called mobile first. It keeps the phone layout plain and safe, and it means that a phone never has to undo rules made for a laptop.
One media query
A media query is a condition around a group of rules. The rules inside apply only while the condition is true:
@media (min-width: 48rem) {min-width: 48rem means "the viewport is at least 48rem wide", which is 768 pixels. Below that, the browser skips every rule inside the braces. The width where the layout changes is called a breakpoint. Choose it where your content needs more room, not for one particular phone. Phones change every year.
A media query does not make a rule more specific. Inside it, .gear is as specific as .gear outside it, so the later rule wins, as in lesson 1. That is one more reason to put the media query at the end of the file.
Images that shrink
An image keeps its own width, even when the screen is narrower:
img {
max-width: 100%;
height: auto;
}max-width: 100% means "never wider than the element it is in". The % unit is a share of that element's width. height: auto lets the browser work out the height from the width, so the image shrinks without being squashed. The width and height attributes on the img, which you met in module 2, still matter: they tell the browser the shape of the image before it arrives, so the page does not jump while it loads.
Worked example
Make a folder called himalaya-trek with three files. The first is the image, mountains.svg. An SVG file is a picture written as text, so you can make it in Visual Studio Code like any other file:
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="320" viewBox="0 0 640 320">
<rect width="640" height="320" fill="#dbe9f6" />
<polygon points="0,320 170,90 300,320" fill="#4a6782" />
<polygon points="200,320 400,40 600,320" fill="#2f4a63" />
<polygon points="350,110 400,40 450,110 425,95 400,115 375,95" fill="#ffffff" />
<polygon points="420,320 560,140 640,230 640,320" fill="#4a6782" />
<rect y="290" width="640" height="30" fill="#5e7d3a" />
</svg>You do not need to understand it. It draws mountains, 640 pixels wide and 320 tall. The second file is index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Himalaya Trek Hire, Pokhara</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Himalaya Trek Hire</h1>
<img src="mountains.svg" alt="Drawing of snow-capped mountains above green hills" width="640" height="320" />
<p>Trekking gear for hire in Pokhara, near the start of the Annapurna treks.</p>
<h2>Gear for hire</h2>
<ul class="gear">
<li class="item">Sleeping bag, warm to minus 15 °C. $3 a day.</li>
<li class="item">Down jacket, sizes S to XL. $2 a day.</li>
<li class="item">Pair of trekking poles. $1 a day.</li>
</ul>
</body>
</html>The third is styles.css:
/* Text #1b2a38 on white is 14.64 to 1, and green #2e5d1f on white is 7.77 to 1. */
/* The small screen first: one column. */
body {
margin: 0;
padding: 0 1rem;
background-color: #ffffff;
color: #1b2a38;
font-family: Verdana, Arial, sans-serif;
line-height: 1.5;
}
h1 {
color: #2e5d1f;
font-size: 1.75rem;
}
img {
max-width: 100%;
height: auto;
}
.gear {
display: flex;
flex-direction: column;
gap: 1.5rem;
padding: 0;
list-style: none;
}
.item {
box-sizing: border-box;
padding: 1rem;
border: 2px solid #2e5d1f;
}
/* From 48rem (768px) wide: a centred column and the gear in a row. */
@media (min-width: 48rem) {
body {
max-width: 60rem;
margin: 0 auto;
padding: 0 2rem;
}
h1 {
font-size: 2.5rem;
}
.gear {
flex-direction: row;
}
.item {
flex-grow: 1;
flex-basis: 15rem;
}
}The rules above the media query are the whole phone layout. The media query changes four things for a wide screen: it centres the page with more padding, makes the heading larger, turns the gear into a row and shares the row between the items.
Test it at 390 pixels
A width of 390 pixels is the width of many current phones. To see the page at that width in Chrome or Edge, open the developer tools and click the button named Toggle device toolbar, at the top of the developer tools. Keep Dimensions at Responsive, and type 390 in the width box. In Firefox, press Ctrl+Shift+M on Windows and Linux, or Cmd+Option+M on macOS, to open Responsive Design Mode, and type 390 as the width.
At 390 pixels, the Computed tab gives these values:
body width: 358px
img width: 358px
img height: 179px
gear flex-direction: column
item width: 358px
h1 font-size: 28pxOne column, 390 minus 32 pixels of padding. The image shrank to 358 pixels and kept its shape: 179 is half of 358, as 320 is half of 640. The gear is in a column, and the media query did nothing. Try to drag the page sideways. It does not move.
Now set the width to 1280:
body width: 960px
body margin-left: 128px
img width: 640px
gear flex-direction: row
item width: 304px
h1 font-size: 40pxThe media query applies. The page is a centred column of 960 pixels, the gear is in a row and the heading is larger. The image is 640 pixels, its own width. max-width lets an image shrink, but never stretches it.
Last, the breakpoint itself:
767 pixels: column
768 pixels: rowAt 768 pixels, which is 48rem, the condition becomes true.
Common mistakes
An image with no max-width
Here is the page without the img rule, at 390 pixels:
img width: 640px
body width: 358pxThe image is 640 pixels wide in a page of 358. It sticks out past the right edge, so the whole page can be dragged sideways, and the text moves with it. This was Anil's problem. One element that is too wide is enough. When a page scrolls sideways, look for the widest thing on it.
The media query first
/* From 48rem (768px) wide: a centred column and the gear in a row. */
@media (min-width: 48rem) {This file has the media query at the top and the phone rules below it. At 1280 pixels:
gear flex-direction: column
h1 font-size: 28px
body margin-left: 0pxThe wide layout is lost. The rules inside the media query are as specific as the phone rules, and the phone rules come later, so they win. Put the media query after the rules it changes.
max-width where you meant min-width
@media (max-width: 48rem) {390 pixels: row
1280 pixels: columnThe layout is upside down: a row on the phone and a column on the laptop. max-width: 48rem means "at most 48rem wide", so the wide rules apply only to small screens. For mobile first, the condition is always min-width.
Think it through
Anil wants a menu next to his name on a laptop, with two links: one to the gear and one that opens an email. On a phone, the menu should sit under the name. Dmitri, a learner, adds it.
Understand. On a small screen, the name and the menu stack. From 48rem, they share one line, name on the left, menu on the right.
Break down. The HTML for the menu. The phone rules. The wide rules.
Plan. He wraps the h1 and a nav with a list of two links in a header. For the phone, the header stays in normal flow, so it needs no rule at all. The list becomes a row with display: flex and gap, with no bullets. For the wide screen, he adds a header rule inside the existing media query: display: flex, justify-content: space-between and align-items: center. He does not add a second media query.
Build. He writes the HTML, the .menu rule with the phone rules, and the header rule inside the media query. He gives the links the green of the heading, which he has already measured: 7.77 to 1.
Test. At 390 pixels, header is block and the menu is under the name. At 768 it is flex, on one line. For the odd case he tries 767, one pixel narrower, and the menu drops under the name again, exactly at the breakpoint.
Reflect. All the wide-screen changes are in one place. Anyone who opens the file can see what changes on a laptop by reading one block.
At work
Sometimes, halfway through a job, you find that your estimate was wrong. Say so as soon as you know, not when the time is up. Early news lets the client choose. Late news only disappoints them.
Dmitri estimated 2 hours to make Anil's page fit a phone. Anil's real page is longer than the example. After one hour, Dmitri found that its price table also needed a fix of its own. He wrote:
Anil, a short update on the phone layout. I estimated 2 hours, and I now expect 3. The photo and the gear list are done. The price table is wider than a phone, and fixing it well needs another hour.
Two choices: I can finish all of it by tomorrow, in 3 hours in total, or stop at 2 hours with the table as it is today. Which do you prefer?
He says what is done, what is left, the new number and the reason, and he offers a choice. Anil decides, and nothing is a surprise.
Your tasks
Task 1: Build and resize
Build the three files and open the page. Look at it at 390, 767, 768 and 1280 pixels in the device toolbar. At each width, try to drag the page sideways.
You are done when you have seen one column at 390 and 767, the gear in a row at 768 and 1280, and no sideways movement at any width.
Task 2: Break it on purpose
Delete the img rule, and look at the page at 390 pixels. Then put it back, move the whole media query to the top of the file, and look at it at 1280 pixels. Put it back at the end when you finish.
You are done when you have seen the page scroll sideways without the img rule, and lose its wide layout with the media query first.
Task 3: Make your own page fit a phone
Take your Kigali Threads page. Check that it has the viewport line. Make sure the styles outside any media query give one column, then add one media query with min-width for the wide layout. Choose its breakpoint by widening the device toolbar until your content looks cramped in one column.
You are done when your page has one column at 390 pixels with nothing past the right edge, and a wider layout above your breakpoint, from one media query.
Recap
- The viewport line makes a phone lay the page out at its real width. Every page needs it.
- Write the phone rules first, outside any media query. Then add the wide-screen rules in one
@media (min-width: ...)block at the end of the file. img { max-width: 100%; height: auto; }lets an image shrink with the screen and keep its shape.- Test at 390 pixels in the device toolbar. If the page moves sideways, find the element that is too wide.
Go deeper
- MDN: Responsive web design explains the viewport line, flexible images and mobile first.
- MDN: Media query fundamentals builds a mobile first page with media queries, one step at a time.
- Chrome for Developers: Simulate mobile devices with device mode shows the device toolbar and how to set a width.
- Firefox Source Docs: Responsive Design Mode gives the same steps for Firefox.