Sub topic 2
Setting the viewport
This chapter assumes you know basic HTML document structure, CSS selectors and the cascade, the box model, and the units px, em, and rem. It explains why a responsive page needs one line in its <head> before any media query will behave as expected.
What the viewport is
The viewport is the area of the browser window where your page is drawn. On a desktop, it is the window minus toolbars and tabs. Resizing the window changes it, and your CSS width-based media queries respond to that change.
Phones complicate this. Browsers distinguish two viewports:
- The layout viewport is the rectangle the browser uses to lay out your page. Percentages,
vwunits, andwidthmedia queries are all computed against it. - The visual viewport is the part of the page the user currently sees. Pinch-zooming shrinks the visual viewport, and the layout viewport stays the same.
The viewport meta tag controls the layout viewport. It does not affect the visual viewport directly, except for the initial zoom level.
The problem the tag solves
When the first smartphones appeared, most websites were built for desktop screens at roughly 960px wide. To avoid showing those pages as broken, mobile browsers began to pretend that the screen was wide. Without further instructions, a mobile browser typically sets the layout viewport to about 980px, renders the page at that width, and then scales the result down to fit the physical screen.
For a page that is not responsive, this default is helpful. For a responsive page, it defeats the purpose. Suppose your CSS contains @media (max-width: 40em) for phones. The browser reports a width of 980px, so the query never matches. The user sees a tiny desktop layout and has to zoom in to read it.
The meta tag
The fix is a <meta> element in the document head:
<meta name="viewport" content="width=device-width, initial-scale=1">It has two directives, separated by a comma:
width=device-widthsets the layout viewport width to the width of the device in CSS pixels. A CSS pixel is not a hardware pixel. A phone with a 1170-hardware-pixel-wide screen typically reports adevice-widthof about 390 CSS pixels, because the browser accounts for the device's pixel density.initial-scale=1sets the first zoom level so that one CSS pixel maps to one device-independent pixel. The page appears at its natural size and is not zoomed in or out.
With the tag in place, the same max-width: 40em query now matches on a phone, because the browser reports a width near 390px.
Here is a complete page you can open on a phone or in 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;
margin: 1rem;
background: #fff8e1;
}
@media (min-width: 40em) {
body {
background: #e3f2fd;
}
}
</style>
</head>
<body>
<h1>Viewport demo</h1>
<p>The background is cream below 40em and light blue at 40em and above.</p>
<p id="info"></p>
<script>
document.getElementById("info").textContent =
"Layout viewport width: " + document.documentElement.clientWidth + "px";
</script>
</body>
</html>Delete the viewport line and reload on a phone. The script will report a value near 980, and the background will stay cream, since a viewport that wide would match the min-width: 40em query. Wait, the reverse happens: with a 980px layout viewport, min-width: 40em (640px) matches, so a phone shows the blue desktop styling. That is the failure the tag prevents.
Other directives
The content attribute accepts more values than the two above. You will see these in older code, and some are harmful.
| Directive | Meaning | Advice |
|---|---|---|
| `width` | Layout viewport width in pixels, or `device-width` | Use `device-width`. A fixed number such as `width=600` locks the layout to one size. |
| `initial-scale` | Starting zoom level | Use `1`. |
| `minimum-scale`, `maximum-scale` | Limits on user zoom | Avoid. Restricting zoom harms accessibility. |
| `user-scalable` | `yes` or `no` to allow pinch zoom | Never set to `no`. |
| `viewport-fit` | `cover` extends the layout under display cutouts such as notches | Use only when you handle safe areas yourself. |
| `interactive-widget` | How the on-screen keyboard resizes the viewport | Optional. Supported in newer Chromium browsers. |
Where to put it
Place the tag inside <head>, early in the document, next to the <meta charset> declaration. The browser needs the viewport information before it lays out the page. If the tag appears late or is injected by JavaScript, some browsers perform an initial layout at the wrong width and then redo it, which can cause a visible jump.
The tag is ignored by desktop browsers. You can keep it on every page without any effect on desktop layouts.
What the tag does not do
The tag only sets the viewport. It does not make a page responsive on its own. A layout with fixed widths still overflows on a narrow screen:
.container {
width: 960px; /* wider than a 390px layout viewport */
}With the tag present, this container is 570px wider than the viewport. The browser shows a horizontal scrollbar, and the user can pan sideways. Replace the fixed width with a flexible one:
.container {
width: 100%;
max-width: 60rem;
margin-inline: auto;
}Later chapters cover flexible units, images, and layouts in detail.
Common errors and gotchas
- Missing tag. Symptom: the page looks like a shrunken desktop site on phones, and no mobile media query matches. Fix: add the tag.
- Only
width=device-width. Some older iOS versions then kept the portrait scale after rotation to landscape, so the page looked zoomed in. Includinginitial-scale=1avoids this. - Wrong attribute name. The tag needs
name="viewport". Typos such asname="viewpoint"are silently ignored. - Semicolons instead of commas. Browsers are lenient about this, but commas are the specified separator.
100vwand scrollbars. On desktop browsers with classic scrollbars,100vwincludes the scrollbar width, so an element set towidth: 100vwcan cause horizontal scrolling. Prefer100%for widths.100vhon mobile. Mobile browsers show and hide the address bar as the user scrolls, so100vhmay be taller than the visible area. Thedvhunit (dynamic viewport height) tracks the visible area, andsvhuses the smallest possible height.
Checking what the browser actually uses
You can read the viewport sizes from JavaScript. This is useful when a query does not match and you need to know why.
console.log("Layout viewport:", document.documentElement.clientWidth);
console.log("Window inner width:", window.innerWidth);
console.log("Visual viewport:", window.visualViewport.width);
console.log("Pixel density:", window.devicePixelRatio);On a correctly configured phone, the layout viewport is a number such as 360 to 430. If you see about 980, the tag is missing or malformed. After pinch-zooming, the visual viewport width becomes smaller, while the layout viewport stays the same.
In browser developer tools, open device emulation and pick a phone profile. Emulation only reproduces the mobile viewport behavior when the profile is in mobile mode, so check that the device toolbar shows a phone, not "Responsive" with a desktop user agent. Chapter 16 covers testing in more depth.
Exercise
A page has @media (max-width: 40em) { nav { display: none; } }, and the viewport meta tag is missing. On a phone, the navigation is still visible. Explain why, and give the line that fixes it.
Show answer
Without the tag, the phone uses a layout viewport of about 980px, which is wider than 40em (640px), so the max-width: 40em query does not match and the navigation stays visible. Adding <meta name="viewport" content="width=device-width, initial-scale=1"> to the head makes the layout viewport equal to the device width, around 390px, and the query matches.
Exercise
Why is <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> a poor choice, even though it appears in many older tutorials?
Show answer
user-scalable=no stops users from pinch-zooming. People with low vision depend on zoom to read text, and blocking it fails WCAG 1.4.4. The tag works without it, so remove it.