Sub topic 13
Keeping mobile pages fast
This chapter assumes you can write mobile-first base styles with min-width media queries. It also assumes you know srcset and sizes from the responsive images chapter and can read the Network and Performance panels in browser developer tools.
Mobile-first CSS gives you a head start on speed, because the smallest screens get the smallest set of rules by default. It does not make a page fast on its own. Phones have slower processors than desktops. Their networks have higher latency and less stable bandwidth. A layout that looks right in a narrow browser window can still take eight seconds to appear on a mid-range phone over a weak connection. This chapter covers the decisions that affect how fast a mobile page loads, renders, and responds.
What "fast" means
Performance is measured from the user's side. Three Core Web Vitals are the usual yardsticks.
| Metric | What it measures | "Good" threshold |
|---|---|---|
| Largest Contentful Paint (LCP) | Time until the largest visible element, often a hero image or heading, is drawn | 2.5 seconds or less |
| Interaction to Next Paint (INP) | How quickly the page responds visually after taps and key presses | 200 milliseconds or less |
| Cumulative Layout Shift (CLS) | How much visible content jumps around while loading | 0.1 or less |
These thresholds are measured at the 75th percentile of real visits. They are not tested on your fast development laptop. Most of the CSS-related work below targets LCP (get the main content drawn sooner) and CLS (stop things from moving).
Images: the biggest lever
Images usually account for most of a page's bytes. You already know srcset, sizes, max-width: 100%, and height: auto. These additional habits matter for speed.
Reserve space and prioritize correctly
<img
src="hero-800.jpg"
srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="100vw"
width="800" height="600"
fetchpriority="high"
alt="A crowded market street at dusk">
<img
src="gallery-1-400.jpg"
srcset="gallery-1-400.jpg 400w, gallery-1-800.jpg 800w"
sizes="(min-width: 48em) 33vw, 100vw"
width="400" height="300"
loading="lazy"
decoding="async"
alt="Stalls selling fruit">widthandheightlet the browser compute the aspect ratio before the file arrives, so the page does not jump when it loads. Yourheight: autorule keeps the ratio when CSS resizes the image.loading="lazy"delays images that are far below the viewport. Use it for below-the-fold images only.fetchpriority="high"tells the browser the image is important. Use it on the one image likely to be your LCP element, not on everything.
Modern formats with `picture`
Formats such as AVIF and WebP are often much smaller than JPEG at similar quality. Use picture so older browsers fall back to a format they understand.
<picture>
<source type="image/avif" srcset="photo-400.avif 400w, photo-800.avif 800w" sizes="100vw">
<source type="image/webp" srcset="photo-400.webp 400w, photo-800.webp 800w" sizes="100vw">
<img src="photo-800.jpg" width="800" height="600" alt="A hiker on a mountain ridge">
</picture>The `display: none` trap
A common desktop-first habit is to hide the large image on phones with display: none. That does not stop the download. An img element still fetches its file when it is hidden. If you need different images at different sizes, use srcset or picture. Do not use two img elements with one hidden.
Background images
For decorative images set in CSS, the mobile-first pattern saves bytes. Browsers only fetch a background image when a rule that uses it matches an element. Put the small image in the base rule and replace it inside a min-width query.
.hero {
background-image: url("hero-small.jpg");
background-size: cover;
min-block-size: 40vh;
}
@media (min-width: 48em) {
.hero {
background-image: url("hero-large.jpg");
min-block-size: 60vh;
}
}A phone downloads only hero-small.jpg. A desktop-first version that sets the large image as the base and overrides it on small screens risks fetching both files, depending on how the rules are written and loaded. This is another practical reason to build up from the base.
CSS delivery
CSS is render-blocking. The browser will not paint a page until it has downloaded and parsed the stylesheets it found in the head. A large stylesheet therefore delays the first paint on every device.
Some practical rules:
- Keep the base stylesheet small. Mobile-first helps, because the base contains single-column layout and typography. Wide-screen additions are the smaller part.
- Avoid
@importinside CSS. Each import is discovered only after the parent file downloads, so the requests happen one after another. Use separatelinkelements or a build step that bundles files. - Split by media when a block is large and only useful on wide screens.
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="wide.css" media="(min-width: 64em)">
<link rel="stylesheet" href="print.css" media="print">The browser still downloads wide.css on a phone, but at a lower priority, and it does not block the first paint when the query does not match. This only pays off for sizable files. For a few kilobytes, one extra request costs more than it saves.
Fonts
Web fonts are another source of delay and shifting. A missing font file can leave text invisible or cause it to jump when the font arrives.
@font-face {
font-family: "Body";
src: url("body-regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
body {
font-family: "Body", system-ui, sans-serif;
}font-display: swapshows text immediately in the fallback font and swaps when the web font loads.- WOFF2 is the compressed format to serve. Every browser that supports web fonts supports it.
- Each weight and style is a separate file. Three weights cost three downloads. Consider a variable font if you need many.
- A fallback that resembles your web font reduces the visible jump on swap. A system font stack avoids the download altogether, which is often the right choice for body text on mobile.
Rendering cost
Download time is only part of the story. A slow phone also struggles with layout and paint work.
Animate cheap properties
Changing width, top, or margin forces the browser to recalculate layout on every frame. Changing transform and opacity can usually be handled without it.
.drawer {
transform: translateX(-100%);
transition: transform 250ms ease-out;
}
.drawer.is-open {
transform: translateX(0);
}Combine this with the prefers-reduced-motion query from the user preferences chapter so animation stays optional.
Skip work for off-screen content
For long pages made of independent sections, content-visibility: auto lets the browser skip layout and paint for sections that are not near the viewport.
.section {
content-visibility: auto;
contain-intrinsic-size: auto 600px;
}contain-intrinsic-size gives skipped sections a placeholder height. Without it, the scrollbar would jump as sections are rendered. Browsers that do not support the property ignore it, so it is safe as an enhancement. Do not apply it to content that anchor links or in-page search must reach reliably without testing it.
Keep selectors and layout simple
Modern engines handle ordinary selectors quickly. The larger costs are deeply nested DOM structures, huge numbers of elements, and layout that depends on many children (for example, thousands of grid items). If a profile shows long "Recalculate Style" or "Layout" tasks, reduce the element count before tuning selectors.
Common mistakes
- Hiding large assets with
display: noneinstead of choosing them withsrcsetorpicture. - Lazy loading the hero image.
- Omitting
widthandheighton images, which causes layout shift. - Loading four font weights where one or two are used.
- Testing only on a fast laptop with a fast connection.
- Making one huge, desktop-first stylesheet and overriding it on phones. Phones then download and parse rules they never use.
Measuring the result
Treat speed as something you check, not something you assume. In Chrome DevTools, use the Network panel to apply a throttling profile such as "Slow 4G", and use the Performance panel with CPU throttling to approximate a slower phone. Lighthouse gives a quick lab report with hints. Lab tools only simulate. Field data, collected from real users through a tool such as the Chrome UX Report or a real-user monitoring script, shows what your audience experiences. The next chapter covers emulators and real-device testing in more detail.
Exercise
A page has a large hero img at the top. On phones, a developer hides it with display: none and shows a smaller image in a second img element. Page weight on phones is still high. Why, and what should replace this approach?
Show answer
Both img elements still download their files, because display: none does not stop an image from loading. Replace the pair with a single img that has srcset and sizes (or a picture element), so the browser fetches only one appropriately sized file. Add width and height to prevent layout shift.
Exercise
Why is it a mistake to add loading="lazy" to the hero image, and which attribute helps the browser load it sooner?
Show answer
Lazy loading postpones the request until the browser has finished layout and decided the image is near the viewport. That delays Largest Contentful Paint. Leave loading off the hero image and add fetchpriority="high" so the browser requests it early.
Exercise
You need a slide-in menu on a low-end phone. Which properties should the transition change, and why?
Show answer
Change transform (and optionally opacity). These can usually be animated without recalculating layout on each frame. Animating left, width, or margin forces layout work for every frame, which causes dropped frames on slow devices.