Sub topic 8
Responsive images and media
Images are usually the heaviest part of a page, and they have fixed pixel dimensions. A layout that reflows from 360 px to 1400 px wide can still break if its images overflow, stretch, or download at the wrong size. This chapter covers the CSS and HTML that make images, video, and embeds follow a mobile-first layout.
It assumes you know basic HTML, the box model, and the viewport meta tag from earlier in this tutorial. You should also be comfortable with rem and % units and with using browser developer tools.
The CSS baseline
Start with the rule that keeps media inside its container:
img,
video {
max-width: 100%;
height: auto;
}max-width: 100% stops an image from growing past its container. It does not stretch smaller images, so a 300 px icon stays 300 px. height: auto keeps the aspect ratio when the width shrinks.
Images are inline elements by default. That leaves a few pixels of space below them, because the image sits on the text baseline. Setting display: block on images that stand alone removes the gap.
Do not use width: 100% here unless you want small images to be stretched and blurry.
Reserve space with width and height attributes
Always put width and height attributes on <img>, as in the example below. Modern browsers use them to compute an aspect ratio before the file arrives. The browser reserves the right amount of space, so text below the image does not jump when the image loads. That jump is called layout shift.
The attributes do not fix the rendered size. With height: auto in your CSS, the attributes only supply the ratio. If you leave height: auto out, the height attribute can override your fluid width and the image gets distorted. This is a common error.
Resolution switching with srcset and sizes
A phone with a 360 px wide layout should not download a 1600 px photo. The srcset and sizes attributes let the browser choose a file.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 48em) 50vw, 100vw"
width="800" height="600"
alt="A hiker on a mountain ridge">Each part has a job:
srcsetlists candidate files. Thewvalue is the file's real width in pixels, not a display size.sizessays how wide the image will be displayed. Here it is 50% of the viewport at 48em and above, and 100% below that.srcis the fallback for browsers that do not understandsrcset.
The browser reads sizes to find the display width in CSS pixels. It multiplies that by the device pixel ratio. It then picks the smallest candidate that covers the result. A 390 px wide phone with a ratio of 3 needs about 1170 px, so it picks photo-1600.jpg. A desktop window at 1280 px shows the image at 640 CSS pixels. On a ratio-1 screen that needs 640 px, so it picks photo-800.jpg.
The browser makes this choice before layout, and before it has loaded your CSS. That is why sizes exists. The browser cannot measure the rendered image first, so you describe the layout to it.
Common srcset errors
- Omitting
sizeswhen usingwdescriptors. The browser assumes100vw. On a two-column layout that makes it download images far larger than needed. - A
sizesvalue that does not match the CSS. The browser trusts it. If you say100vwbut the image is 300 px wide in the layout, you waste bytes. If you say20vwfor a full-width image, it looks blurry. - Using media conditions in
sizesthat disagree with your breakpoints. Keep the breakpoint insizesequal to the one in your CSS. - Treating the choice as a command. The browser may pick a larger file than you expect, for example because of a cached image or data-saver settings. Do not rely on a specific file being chosen.
- Using
wdescriptors for fixed-size images. For a logo that is always 120 px wide, use density descriptors:srcset="logo-120.png 1x, logo-240.png 2x". You do not needsizesthere.
Art direction with picture
srcset switches between sizes of the same image. Sometimes you need a different crop. A wide landscape banner on a desktop may be unreadable on a phone, where a tighter square crop works better. The <picture> element handles this.
<picture>
<source
media="(min-width: 48em)"
srcset="hero-wide-1200.jpg 1200w, hero-wide-2400.jpg 2400w"
sizes="100vw"
width="1200" height="500">
<img
src="hero-square-600.jpg"
srcset="hero-square-600.jpg 600w, hero-square-1200.jpg 1200w"
sizes="100vw"
width="600" height="600"
alt="A hiker standing on a mountain ridge at sunrise">
</picture>
</code></pre>The <img> is the mobile-first default. The <source> with media="(min-width: 48em)" overrides it on wider screens. The browser takes the first <source> whose media matches. Order matters.
Unlike srcset alone, the media condition on a <source> is a rule the browser must follow. Use <picture> only when the crop really changes. Otherwise srcset is simpler.
You can also use <picture> to offer newer formats. A <source type="image/avif"> placed before a JPEG fallback lets supporting browsers pick the smaller file.
| Need | Use | Browser choice |
|---|---|---|
| Same image, different file sizes | `srcset` with `sizes` | Browser decides |
| Different crop or composition | `<picture>` with `media` | Your rule is followed |
| Different file formats | `<picture>` with `type` | First supported type wins |
| Fixed-size image, sharper on dense screens | `srcset` with `1x`, `2x` | Browser decides |
Controlling shape with aspect-ratio and object-fit
Cards often need images with identical proportions, even when the source files differ. Combine aspect-ratio with object-fit:
.thumb {
display: block;
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}aspect-ratio fixes the box shape. object-fit: cover scales the image to fill the box and crops the overflow. Use contain to show the whole image with empty space around it. object-position moves the crop, for example object-position: center top to keep faces in view.
Video and embeds
Native <video> is covered by the same baseline rule. Embedded <iframe> content such as a video player is different, because an iframe has no intrinsic aspect ratio. Give its wrapper one:
.video-frame {
aspect-ratio: 16 / 9;
}
.video-frame iframe {
width: 100%;
height: 100%;
border: 0;
}Older tutorials use a "padding-top: 56.25%" trick for this. aspect-ratio replaces it in current browsers.
For <video>, set preload="metadata" so a phone does not download the whole file in advance. Add a poster image so the player area has something to show.
Background images in CSS
CSS backgrounds do not support srcset. Use the mobile-first pattern you already know: a small file in the base rule and a larger one inside a min-width query.
.hero {
min-height: 40vh;
background-image: url("hero-800.jpg");
background-size: cover;
background-position: center;
}
@media (min-width: 48em) {
.hero {
background-image: url("hero-1600.jpg");
}
}A browser only downloads a background image when a rule that uses it matches. A phone never fetches hero-1600.jpg. For high-density screens, image-set() offers the same choice as 1x and 2x descriptors.
Use <img> for content that carries meaning. A CSS background has no alt text, so screen readers cannot describe it.
Loading behavior
Two attributes help on slow mobile connections:
loading="lazy"delays images until the user scrolls near them. Use it on images below the first screen.decoding="async"lets the browser decode the image without blocking other work.
Do not lazy-load the largest image visible on first paint, such as the hero. It delays the moment the page looks loaded. Leave that one eager, and for the single most important image consider fetchpriority="high".
A checklist for each image
- Does it have
width,height, and meaningfulalttext (or an emptyaltif decorative)? - Is
max-width: 100%withheight: autoapplied? - Do the
sizesvalues match the real layout widths? - Does the crop need to change on small screens? If so, use
<picture>. - Is it below the first screen? If so, add
loading="lazy".
Exercise
A product card shows an image at full container width below 48em and at 33vw from 48em up. You write srcset="p-300.jpg 300w, p-600.jpg 600w, p-1200.jpg 1200w" but leave out sizes. A 1280 px desktop browser then downloads p-1200.jpg. What should you add, and which file should the browser prefer at a pixel ratio of 1?
Show answer
Add sizes="(min-width: 48em) 33vw, 100vw". Without sizes the browser assumes 100vw, which is 1280 px, so it picks the 1200 w file. With the attribute, the display width is about 422 px (33% of 1280), so the smallest candidate that covers it is p-600.jpg.
Exercise
A hero banner needs a tall crop on phones and a wide crop at 48em and above. Which element do you use, and why is srcset alone not enough?
Show answer
Use <picture> with a <source media="(min-width: 48em)"> for the wide crop and an <img> with the tall crop as the default. srcset alone lets the browser choose between sizes of one image, but it cannot be told to switch to a different crop at a given width.