Sub topic 3
Setting the viewport so the page renders at device width
This chapter assumes you know basic HTML structure, CSS units and the box model, and how to open your browser's developer tools. It covers the viewport meta tag, what it changes inside the browser, and the mistakes that most often break it.
Why mobile browsers need a hint
Early smartphones had to cope with websites built for desktop monitors. Those sites were typically about 980 pixels wide. If a phone had rendered them at the real screen width of roughly 320 to 430 CSS pixels, the layout would have collapsed. So mobile browsers invented a workaround: they lay the page out on a wide imaginary canvas and then shrink the result to fit the screen.
That workaround is still the default today. If your page has no viewport instruction, a mobile browser assumes it is an old desktop page. Your carefully built single-column layout will be drawn at about 980 CSS pixels wide and scaled down. Text becomes tiny, and the user must pinch and zoom to read it.
The viewport meta tag tells the browser that the page was designed for small screens, so the workaround is not needed.
The three viewports
"Viewport" means different things depending on context. Mobile browsers track more than one.
- The layout viewport is the rectangle that CSS layout uses. Percentages,
vwunits and media queries are resolved against it. The viewport meta tag controls its width. - The visual viewport is the part of the page the user can currently see. Pinch-zooming makes it smaller. Showing the on-screen keyboard also shrinks it.
- The ideal viewport is the layout viewport width that suits the device. This is the device width in CSS pixels, which is not the same as hardware pixels.
A CSS pixel is an abstract unit. A phone with a 1170-pixel-wide display may report a width of 390 CSS pixels, because each CSS pixel is drawn using three hardware pixels. Your CSS only ever deals with CSS pixels.
The standard tag
Put this line in the <head> of every page:
<meta name="viewport" content="width=device-width, initial-scale=1">It contains two instructions.
width=device-widthsets the layout viewport width to the device's ideal width in CSS pixels.initial-scale=1sets the first zoom level so that one CSS pixel maps to one CSS pixel of the ideal viewport. In other words, the page loads without any zoom.
In practice, each instruction on its own is mostly enough on modern browsers. Older versions of iOS Safari had a bug where rotating a page to landscape would enlarge it when only width=device-width was set. Including both is the safe and conventional choice.
A complete page to test with
The following file is small enough to try right now. Save it as viewport-demo.html and open it on a phone, or in your browser's device emulation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Viewport demo</title>
<style>
body {
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5;
margin: 0;
padding: 1rem;
}
#width-report {
font-weight: bold;
}
</style>
</head>
<body>
<h1>Viewport demo</h1>
<p>The layout viewport is <span id="width-report"></span> CSS pixels wide.</p>
<script>
const report = document.getElementById("width-report");
function update() {
report.textContent = document.documentElement.clientWidth;
}
update();
window.addEventListener("resize", update);
</script>
</body>
</html>On a typical phone the number printed is between about 360 and 430. Now delete the <meta name="viewport"> line and reload on a real phone. The number jumps to about 980 and the text shrinks. This is the quickest way to see what the tag does.
Desktop browsers ignore the tag, and so does desktop-style window resizing. To see the effect without a phone, use the device toolbar in your browser's developer tools. Emulation can lag behind real devices, so reload the page after toggling the emulator.
Optional values and what they do
The content attribute accepts a comma-separated list of properties. Most pages need only the two above, but you should recognise the others.
| Property | What it does | Advice |
|---|---|---|
| `width` | Sets the layout viewport width. Use `device-width` or a number of CSS pixels. | Use `device-width`. A fixed number such as `width=600` makes the page scale on any screen that is not 600 pixels wide. |
| `initial-scale` | Sets the starting zoom level. | Use `1`. |
| `minimum-scale` | Sets the lowest zoom level allowed. | Leave unset. |
| `maximum-scale` | Sets the highest zoom level allowed. | Do not set it below `5`, and preferably leave it unset. |
| `user-scalable` | Allows (`yes`) or blocks (`no`) pinch zoom. | Never use `no`. |
| `viewport-fit` | Controls use of the screen area around notches and rounded corners. Values are `auto`, `contain` and `cover`. | Use `cover` only if you also handle safe-area insets. |
| `interactive-widget` | Sets how the on-screen keyboard affects the viewport. Values are `resizes-visual`, `resizes-content` and `overlays-content`. | Rarely needed. Support varies. |
Do not disable zoom
Many tutorials from the early smartphone era suggest this tag:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">This is an accessibility failure. People with low vision rely on pinch zoom to read text. Web Content Accessibility Guidelines (WCAG) success criterion 1.4.4, Resize Text, requires that text can be resized to 200 percent without loss of content. Blocking zoom stops users from doing that.
Some developers add maximum-scale=1 to stop iOS Safari from zooming into a form field when it receives focus. That zoom happens when an input's font size is below 16 pixels. The correct fix is to set the input font size to at least 1rem, not to block zoom for everyone.
input,
select,
textarea {
font: inherit;
font-size: 1rem;
}How the tag connects to the rest of mobile-first CSS
The viewport tag is the base that everything else in this approach rests on. Two features depend on it directly.
Media queries. A rule such as @media (min-width: 40em) is resolved against the layout viewport width. Without the tag, a phone reports about 980 CSS pixels. Your min-width queries for tablets and desktops then fire on a phone, and your mobile-first base styles are never shown. The page looks like the desktop layout, shrunk.
Relative units. vw units and percentage widths are also resolved against the layout viewport. With a wrong viewport, a width: 100% box is 980 pixels wide before scaling. Fluid layout only means something when the viewport is the true device width.
The tag does not make a page responsive on its own. It only removes the scaling so that your CSS can respond to the real width.
Common mistakes
- Missing tag. The page renders at about 980 pixels and is scaled down. This is the most common cause of "my media queries do not work on the phone".
- Wrong
nameor typos. Browsers silently ignore unknown names and properties.name="viewport"must be exact. Writingdevice-withorinitial_scaleproduces no error. - Tag placed outside
<head>. Put it in the head, early, before stylesheets that may depend on it. Browsers read it while parsing, and placing it late can delay or misapply the layout. - Fixed pixel width. A tag such as
width=1024forces a 1024-pixel layout and scaling on smaller devices. It is occasionally used deliberately for legacy pages that cannot be made fluid, but it is the opposite of mobile-first. - Content wider than the viewport. Even with the correct tag, a single wide element such as a table, a pre-formatted block or an image with a fixed width can overflow. The browser then allows horizontal scrolling or shrinks the page to fit the wide item. This is a CSS problem, not a viewport problem.
- Separate mobile site. Serving an
m.site with its own tags is a dated approach. A single responsive page with one tag is simpler to maintain.
Finding overflow
If the page seems zoomed out even though the tag is present, find the element that is too wide. Paste this into the developer tools console:
const vw = document.documentElement.clientWidth;
document.querySelectorAll("body *").forEach((el) => {
const box = el.getBoundingClientRect();
if (box.right > vw + 1) {
console.log("Wider than the viewport:", el, Math.round(box.right));
}
});The console lists each element whose right edge extends beyond the viewport. Fix those with max-width: 100%, overflow-x: auto on a wrapper, or by letting text wrap.
Related CSS: viewport units
The viewport tag sets the layout viewport. CSS also offers units based on it: vw and vh (1% of the width or height), plus newer svh, lvh and dvh.
On phones, browser toolbars appear and disappear as the user scrolls, so the visible height changes. This makes plain 100vh unreliable. It usually equals the tallest state of the viewport, so content can be hidden behind the toolbar.
svhis the small viewport height, with toolbars showing.lvhis the large viewport height, with toolbars hidden.dvhis the dynamic viewport height, which follows the current state.
.hero {
min-block-size: 100vh; /* fallback for older browsers */
min-block-size: 100svh; /* safe height with toolbars shown */
}The second declaration is ignored by browsers that do not understand svh, so the first remains as a fallback.
A short checklist
- Every page has
<meta name="viewport" content="width=device-width, initial-scale=1">in the head. - Zoom is never disabled.
- Input font sizes are at least
1rem. - No element is wider than the viewport at 320 CSS pixels.
- Checked once on a real device, not only in the emulator.
Exercise
A page has a mobile-first stylesheet with a rule inside @media (min-width: 64em) that creates three columns. On a phone, the user sees the three-column layout, shrunk to a tiny size. The head contains <meta name="viewport" content="width=device-width"> spelled correctly, but a colleague accidentally deleted it during a refactor. What is the cause, what width does the phone report, and what exact tag should you restore?
Show answer
Without the viewport tag, the phone uses its default layout width of about 980 CSS pixels. 64em is 1024 pixels at the default 16-pixel font size, so the query is close to matching and may match on some devices, and the page is scaled down to fit the screen. Either way the layout is not based on the real device width, so the three-column layout appears tiny. Restore <meta name="viewport" content="width=device-width, initial-scale=1"> in the <head>. The width then becomes the real device width, for example 390 CSS pixels, so the min-width: 64em query no longer matches and the single-column base layout shows.
Exercise
A teammate wants to add maximum-scale=1 so that iOS Safari stops zooming into the email input when it is focused. What is the problem with this, and what is the better fix?
Show answer
Blocking zoom stops users with low vision from enlarging text, which fails WCAG 1.4.4. The focus zoom happens because the input's font size is below 16 pixels. The better fix is to set the input's font size to at least 1rem (for example font: inherit; font-size: 1rem;) and leave zoom enabled.
Exercise
Your page has the correct viewport tag, but on a phone it still looks zoomed out and can scroll sideways. What is the likely cause and how can you find it?
Show answer
An element is wider than the viewport, such as a fixed-width table, image or code block, which forces the browser to widen or scale the page. Find it by comparing each element's right edge with document.documentElement.clientWidth in the console, as in the overflow script above, then constrain the element with max-width: 100%, wrap it in a container with overflow-x: auto, or let its content wrap.