Sub topic 11
Adapt the layout to small screens
The horizontal bar from the earlier chapters works well on a desktop. On a phone it does not. Four links with 1rem of padding on each side can fit in 360 pixels, but a bar with eight links cannot. This chapter shows how to detect a narrow screen, change the layout for it, and avoid the usual mistakes.
This chapter assumes you have the nav, ul, li and a markup and the Flexbox bar from the previous chapters. It also assumes you know CSS specificity and the cascade. The JavaScript that opens the menu belongs to the next chapter. Here you only need to understand the CSS that makes it possible.
What goes wrong on a narrow screen
A flex container with display: flex keeps its items on one line by default (flex-wrap: nowrap). Flex items may shrink, but only down to their minimum content width. Link text does not break inside a word, so the items eventually overflow the container. The result is either a horizontal scrollbar on the whole page or links clipped at the edge.
The page may also look too small, not only too wide. That has a different cause, covered next.
Tell mobile browsers the real width
Mobile browsers pretend the screen is about 980 pixels wide unless the page says otherwise. They render at that width and shrink the result to fit. Your media queries then see a wide viewport and never fire. Add this to the <head> of every page:
<meta name="viewport" content="width=device-width, initial-scale=1">This sets the layout viewport to the device width in CSS pixels. Without it, nothing else in this chapter works on a real phone, even though it works when you resize a desktop window.
Do not add user-scalable=no or maximum-scale=1. They block pinch zoom, which many low-vision users rely on.
Media queries
A media query applies a block of rules only when a condition is true. The condition used for navigation is the viewport width:
@media (max-width: 40rem) {
/* rules for viewports up to 40rem wide */
}Write breakpoints in rem or em, not px. In media queries these units are relative to the browser's default font size, not to any font size you set in your CSS. At the default 16px, 40rem is 640px. A user who has raised their default font size to 24px reaches the same breakpoint at 960px. This matters because larger text makes the bar run out of room sooner. A px breakpoint ignores that and lets the bar overflow.
Choose the breakpoint from your content, not from a device list. Widen the window until the links start to crowd, then set the breakpoint just above that width. A bar with four short links may need 30rem. A bar with nine may need 60rem.
Pick a strategy
There are three common ways to handle a bar that does not fit.
| Strategy | CSS needed | JavaScript | Best for |
|---|---|---|---|
| Wrap onto several rows | `flex-wrap: wrap` | None | Four to six short links |
| Scroll horizontally | `overflow-x: auto` on the list | None | Tab-like bars where scrolling is expected |
| Collapse behind a toggle | Media query, hidden list, button | A few lines | Many links, or a bar that must stay one row tall |
Wrapping
Wrapping is the cheapest fix and has no failure mode beyond looking untidy:
.nav-list {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
margin: 0;
padding: 0;
list-style: none;
background: #1f2937;
}Links that do not fit move to a second row. The background still covers every row because it belongs to the ul. The drawback is that the bar's height changes with the screen width. That makes a sticky bar costly, because it covers more of a small screen.
Collapsing behind a toggle
This is the pattern most sites use. Below the breakpoint, the list is hidden and a button appears. Above it, the button is hidden and the list is a row. Here is the button markup:
<button class="nav-toggle" aria-expanded="false" aria-controls="nav-list">Menu</button>Here is the CSS:
.nav-toggle {
display: none;
}
@media (max-width: 40rem) {
.nav-toggle {
display: block;
}
.nav-list {
display: none;
flex-direction: column;
}
.nav-list.is-open {
display: flex;
}
}Reading it from the top:
- Outside the media query, the button is hidden. Wide screens never see it, and the list keeps the
display: flexrow layout from earlier. - Inside the media query, the button becomes visible.
- The list gets
display: none, which removes it from the page entirely. flex-direction: columnstacks the links. This changes only the main axis of the container and keeps every other rule. The links keepdisplay: blockand their padding, so each one becomes a full-width row..nav-list.is-openputsdisplay: flexback when JavaScript adds the class.
The last rule only works because of specificity. .nav-list has a specificity of one class. .nav-list.is-open has two, so it wins regardless of order. If you had written .is-open { display: flex } with one class, the later rule in the file would win, and a mistake in ordering would silently break the menu.
Mobile-first or desktop-first
The example above is desktop-first. The base styles describe the wide layout, and max-width queries undo parts of it for small screens. The alternative is mobile-first. The base styles describe the narrow layout, and min-width queries add the wide one:
.nav-list {
display: none;
flex-direction: column;
margin: 0;
padding: 0;
list-style: none;
background: #1f2937;
}
.nav-list.is-open {
display: flex;
}
.nav-list a {
display: block;
padding: 0.75rem 1rem;
color: #ffffff;
text-decoration: none;
}
.nav-toggle {
display: block;
}
@media (min-width: 40rem) {
.nav-toggle {
display: none;
}
.nav-list {
display: flex;
flex-direction: row;
gap: 0.25rem;
}
}Both approaches give the same result on screen. Mobile-first has one practical advantage. A browser that does not understand media queries, or a failed stylesheet load, falls back to the simplest layout. It also tends to need fewer overrides, because the narrow layout is usually the simpler one. Pick one direction for the whole stylesheet. Mixing min-width and max-width queries makes the cascade hard to reason about.
The two directions share a boundary trap. At exactly 40rem, both (max-width: 40rem) and (min-width: 40rem) match. That is harmless if you use only one kind. If you must use both, write one of them as a range such as (width < 40rem). Modern browsers support this range syntax.
Gotchas
The hidden list is gone for everyone
display: none removes the list from the accessibility tree and from the tab order. That is what you want while the menu is closed. It also means that if the toggle script fails to load, narrow-screen users have no navigation at all. Two ways to reduce that risk:
- Add a
jsclass to<html>with a one-line inline script, and write the hiding rule as.js .nav-list. Without JavaScript the list stays visible as a column. - Keep a plain link to a sitemap or footer navigation on the page.
State can go out of sync with width
Suppose a user opens the menu on a narrow window and then widens the window. The is-open class stays on the list. At wide widths the class has no visible effect, because the list is already display: flex. But aria-expanded="true" is now stale, and the button is hidden. Narrowing the window again shows the menu open. If that bothers you, reset the state when a matchMedia listener reports the breakpoint was crossed. For a small site, most teams accept the quirk.
Dropdowns break in a column
The submenu from the dropdown chapter uses position: absolute. In a stacked menu, it overlays the links below it. Hover also does not exist on touch screens. In the narrow layout, switch submenus back to the normal flow:
@media (max-width: 40rem) {
.submenu {
position: static;
display: block;
padding-left: 1rem;
}
}This shows submenu items as indented rows under their parent. It avoids any need for hover on touch devices. The cost is a longer menu, which is usually acceptable.
A tall sticky menu can trap the page
If the bar is position: sticky and the open list is taller than the screen, the bottom links sit below the viewport. Because the bar sticks, scrolling the page does not bring them into view. Cap the height and let the list scroll on its own:
@media (max-width: 40rem) {
.nav-list {
max-height: calc(100vh - 3rem);
overflow-y: auto;
}
}The 3rem is an estimate of the toggle button's height. Adjust it to match your design.
Touch targets
Padding of 0.75rem above and below a line of text gives a link a height of about 48px at the default font size. That is comfortable for a finger. If you shrink the padding to fit more links on a phone, the bar becomes harder to use. WCAG 2.2 sets a minimum target size of 24 by 24 CSS pixels, and recommends 44 by 44 for comfort.
Test it properly
- Open your browser's developer tools and switch to responsive design mode. Drag the width from wide to about 320px and watch where the layout changes.
- Test on a real phone at least once. It is the only way to confirm the viewport meta tag works.
- Zoom the desktop browser to 200% and 400%. This simulates large text and a narrow viewport. WCAG asks that content reflow at 320 CSS pixels wide without horizontal scrolling. Because the breakpoint uses
rem, the collapsed layout should appear as you zoom. - Use only the keyboard in the narrow layout. Check that you can reach the toggle button, that Enter or Space opens the menu, and that Tab then moves through the links in order.
Summary of the working model
- The viewport meta tag makes the browser report its true width.
- A media query chooses between two layouts at a width you pick from your content, in
rem. - The narrow layout stacks the links with
flex-direction: columnand optionally hides them behind a toggle. - The
.is-openclass works because its selector is more specific than the rule that hides the list. - Check the side effects: dropdowns, sticky height, stale ARIA state, and what happens without JavaScript.
Exercise
A colleague writes @media (max-width: 640px) for the collapse breakpoint. A user with a browser default font size of 24px says the bar overflows on their 800px-wide window. Explain why, and give a fix.
Show answer
Pixel breakpoints ignore the user's font size. At 24px text the links are 1.5 times wider, so the bar needs more room, but the query still waits until the viewport is 640px or narrower, and 800px is above that. The links overflow before the collapse applies. Use rem: @media (max-width: 40rem). In media queries, rem is relative to the browser default font size, so the breakpoint becomes 960px for this user and the menu collapses at 800px.
Exercise
You write .is-open { display: flex; } (one class) before the media query block that contains .nav-list { display: none; } (one class). On a narrow screen, clicking the toggle adds is-open but the menu stays hidden. Why does this happen, and what is the most robust fix?
Show answer
Both selectors have the same specificity, so the later rule in the file wins. The display: none rule inside the media query comes after .is-open, so it overrides it. The most robust fix is to raise the specificity of the open rule with .nav-list.is-open { display: flex; }, which wins regardless of source order. Moving the rule after the media query also works but depends on order.
Exercise
Your narrow-screen nav is sticky and the open menu has 14 links. On a short phone in landscape, the last links cannot be reached. What CSS fixes this?
Show answer
Limit the height of the open list and let it scroll on its own, for example .nav-list { max-height: calc(100vh - 3rem); overflow-y: auto; } inside the narrow media query. The sticky bar then never exceeds the viewport, and the list scrolls inside it.