Sub topic 2
Responsive foundations: the viewport tag and media queries
This chapter assumes you can write basic HTML with semantic elements, lay out a row of items with flexbox, and select an element in JavaScript to attach an event listener. Everything in the later navigation patterns (hamburger menu, tab bar, priority menu) rests on two browser features covered here: the viewport meta tag and CSS media queries. If either is wrong, the navigation will look broken on a phone no matter how well you build it.
What the viewport tag does
Before smartphones, almost every website assumed a window at least 800 to 1000 pixels wide. When phones began browsing the web, they needed to show those sites without breaking them. Mobile browsers therefore render a page into a wide virtual canvas, usually about 980 CSS pixels, and then shrink the result to fit the screen. This canvas is the layout viewport. The part of it you can see on screen is the visual viewport.
That default has a consequence for navigation. If you do not opt out, your page is laid out as if the screen were 980 pixels wide. Your media queries evaluate against 980, so the "small screen" styles never apply. The user gets a tiny desktop page and has to pinch-zoom to read it.
The viewport meta tag opts out. It goes in the <head> of every page:
<meta name="viewport" content="width=device-width, initial-scale=1">It sets two values:
width=device-widthmakes the layout viewport as wide as the device's screen, measured in CSS pixels.initial-scale=1sets the starting zoom so that one CSS pixel maps to one unit of the layout viewport, without extra zoom.
CSS pixels and device pixels
A CSS pixel is not a hardware pixel. A phone with a 1170-pixel-wide display and a device pixel ratio of 3 reports a width of 390 CSS pixels. Your media queries, px values, and window.innerWidth all use CSS pixels. This is why a 48-pixel touch target stays physically about the same size across phones with very different resolutions.
See it for yourself
This page reports the width the browser actually uses. Open it on a phone or in a device emulator, then delete the meta tag and reload.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Viewport check</title>
</head>
<body>
<p id="report"></p>
<script>
const report = document.getElementById('report');
function show() {
report.textContent =
'Layout width: ' + window.innerWidth + ' CSS px, ' +
'pixel ratio: ' + window.devicePixelRatio;
}
window.addEventListener('resize', show);
show();
</script>
</body>
</html>With the tag, a typical phone reports a number between about 360 and 430. Without it, the number jumps to roughly 980.
What not to put in the tag
You will see copied snippets that add maximum-scale=1 or user-scalable=no. Do not use them. They block pinch-zoom, which people with low vision rely on. They also fail WCAG success criterion 1.4.4 (Resize Text). Browsers on some platforms now ignore these values, but the failure still shows up in accessibility audits.
One more value belongs in the tag later. The bottom tab bar chapter uses viewport-fit=cover so that env(safe-area-inset-bottom) returns real values on phones with a notch or home indicator. You do not need it yet.
Media queries
A media query is a condition attached to a block of CSS. The block applies only when the condition is true. The condition is re-evaluated as the window resizes or the device rotates.
@media (min-width: 48em) {
/* rules here apply only when the viewport is at least 48em wide */
}The width tested by min-width and max-width is the viewport width in CSS pixels, which is the number the viewport tag controls. That is why the two features belong together.
Mobile-first with min-width
There are two ways to write breakpoints:
| Approach | Base styles are for | Queries use | Effect on small screens |
|---|---|---|---|
| Mobile-first | Small screens | `min-width` | Phones download and parse only simple rules, then wider screens add to them |
| Desktop-first | Large screens | `max-width` | Phones must undo desktop rules, which means more overrides and more mistakes |
Use mobile-first for navigation. The default state of a nav on a small screen is a stacked list of full-width links. The wide layout is an enhancement you add once there is room. If the stylesheet fails to load a query, or the browser is old, the user still gets a working, readable menu.
Here is that idea applied to a nav. The base rules produce a vertical list. At 48em the list becomes a horizontal row.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mobile-first navigation</title>
<style>
nav ul {
list-style: none;
margin: 0;
padding: 0;
}
nav a {
display: block;
padding: 0.75rem 1rem;
}
@media (min-width: 48em) {
nav ul {
display: flex;
gap: 1rem;
}
}
</style>
</head>
<body>
<nav aria-label="Main">
<ul>
<li><a href="/products">Products</a></li>
<li><a href="/pricing">Pricing</a></li>
<li><a href="/docs">Docs</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</body>
</html>Resize the window across 768 pixels and the list switches from a column to a row. The hamburger chapter extends this exact structure by hiding the list on small screens and revealing it with a button.
Use em for breakpoints
The examples use 48em rather than 768px. Inside a media query, 1em equals the browser's default font size, which is normally 16px, so 48em is 768px at default settings. The difference appears when a user raises the default font size in their browser settings. Their 48em becomes wider in pixels, so the layout switches to the compact version earlier, when a horizontal row would no longer fit the larger text. Pixel breakpoints ignore that setting, and a nav that fit at 768px can overflow once the text is bigger.
In a media query, em is not affected by a font-size you set on html or body. It always refers to the browser default. That is predictable, but it surprises people who expect 1em to follow their stylesheet.
Choose breakpoints from the content
Do not pick breakpoints from a list of device sizes. Devices change every year, and foldables and split-screen windows produce widths that match no list. Pick them by watching your design.
- Start with the narrowest window you support, around 320 CSS pixels.
- Widen it slowly.
- Note the width where the layout starts to look wrong. For a nav, this is the width where the links no longer fit on one line.
- Add a breakpoint there.
For a navigation with four short links, that point might be near 40em. For one with eight links, it will be much larger. The priority menu chapter avoids the problem for a long list by measuring the available space with JavaScript instead of guessing at a width.
Range syntax
Current browsers also support a range syntax that reads more like math:
@media (width >= 48em) {
nav ul {
display: flex;
}
}It means the same as (min-width: 48em). It also allows two-sided ranges such as (30em <= width < 48em), which avoids the off-by-one confusion of mixing min-width with max-width. The older form has wider support, so check your target browsers before choosing. This tutorial uses min-width.
Features beyond width
Width is not the only thing that matters for navigation. Two other media features guard against common mistakes.
(hover: hover)is true when the main input device can hover, such as a mouse. Phones report(hover: none). Use it so that dropdown menus opened on hover do not become unreachable on a touch screen.(pointer: coarse)is true when the main input is imprecise, such as a finger. Use it to enlarge targets.
@media (pointer: coarse) {
nav a {
min-height: 48px;
}
}A small laptop can have a narrow window and a mouse. A large tablet can have a wide window and only touch. Width alone does not tell you which one you have, so test the input type when the behavior depends on it.
prefers-reduced-motion: reduce is a third useful query. When a menu slides open with an animation, wrap the animation in @media (prefers-reduced-motion: no-preference) so that people who asked their system for less motion get an instant change.
Reading the same query in JavaScript
Sometimes script must know which layout is active. For example, a menu open on a phone should reset when the window grows to the wide layout. Use window.matchMedia with the same query string as your CSS, instead of reading innerWidth and repeating the number in a second place.
const wide = window.matchMedia('(min-width: 48em)');
function applyLayout(query) {
document.documentElement.dataset.layout = query.matches ? 'wide' : 'narrow';
}
wide.addEventListener('change', applyLayout);
applyLayout(wide);The change event fires only when the result flips from false to true or the reverse. It does not fire on every pixel of a resize, which makes it cheaper than a resize listener. The same string appears in your CSS and your script, so keep it in one place if you can, such as a constant at the top of the file.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Phone shows a tiny desktop page | Viewport meta tag missing, or placed outside `<head>` | Add the tag inside `<head>` |
| Media query works in a resized desktop window but not on the phone | Tag missing, or a typo such as `device_width` | Use `width=device-width` exactly |
| Page is wider than the screen and scrolls sideways | An element with a fixed width or long unbroken content is wider than the viewport | Use `max-width: 100%` and test at 320px |
| Layout flips at a surprising width | Mixed `px` and `em` breakpoints, or overlapping `min-width` and `max-width` | Use one unit and one direction |
| Landscape phone gets the desktop nav | Width alone triggered the wide layout while the screen is still short and touch-driven | Test `pointer` and `hover` too, and check landscape |
| Users cannot zoom | `user-scalable=no` or `maximum-scale=1` in the tag | Remove them |
What carries forward
The next chapters rely on three facts from this one:
- The viewport tag makes small-screen media queries fire on phones.
- Mobile-first rules with
min-widthinemgive you a working default and a wide-screen enhancement. matchMedialets JavaScript and CSS agree on which layout is active.
Exercise
A page has no viewport meta tag. It contains @media (min-width: 48em) { nav ul { display: flex; } } and a stacked default for nav ul. On a phone with a 390 CSS pixel screen, which layout does the nav get, and why? What one line fixes it?
Show answer
The nav gets the wide, flex layout. Without the tag, the phone lays the page out on a canvas about 980 CSS pixels wide, so the query min-width: 48em (768px) is true, and the browser then shrinks the page to fit. Adding <meta name="viewport" content="width=device-width, initial-scale=1"> inside <head> makes the layout width 390px, so the query is false and the stacked default applies.
Exercise
Why is @media (min-width: 48em) a better choice than @media (min-width: 768px) for a nav breakpoint, and why is it a bad idea to add user-scalable=no to the viewport tag?
Show answer
In a media query, em is based on the browser's default font size, so if a user increases that setting, the wide layout is delayed until there is room for the larger text, while a pixel breakpoint ignores the setting and can cause overflow. user-scalable=no blocks pinch-zoom, which people with low vision need, and it fails WCAG 1.4.4 (Resize Text).