Responsive HTML: Viewport and Responsive Images
Learn responsive HTML basics with the viewport meta tag, flexible images, srcset, sizes and the picture element.
Set the viewport
On mobile devices, the viewport meta tag tells the browser to use the device width as the page width. It is a standard starting point, but it does not make a fixed-width layout responsive by itself; use flexible CSS sizes and layouts as well.
<meta name="viewport" content="width=device-width, initial-scale=1">
Let images fit their layout
CSS typically keeps an image inside its container with max-width: 100%. Include intrinsic width and height attributes so browsers can reserve the right aspect ratio while an image loads.
<img src="mountain.jpg" width="1200" height="800"
alt="Mountain landscape at sunrise">
img {
max-width: 100%;
height: auto;
}
The HTML dimensions describe the source image's proportions; this CSS lets it shrink to fit a narrow container without stretching. Continue with the CSS responsive design lesson for flexible page layouts.
Offer multiple image sizes
Use srcset with width descriptors such as 400w and 800w to offer several image files. With those descriptors, sizes describes the image's expected layout width at different viewport sizes; the browser uses that hint and the device pixel density to choose a suitable file. Keep the dimensions in the example consistent with the actual image files.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 800px"
width="1200" height="800"
alt="A red kayak on a calm lake">
Use picture for art direction
The <picture> element can offer different crops with <source media>. Keep an <img> fallback inside it and provide useful alternative text there.
<picture>
<source media="(max-width: 600px)" srcset="portrait-crop.jpg">
<img src="wide-photo.jpg" width="1200" height="800" alt="A red kayak on a calm lake">
</picture>
Check a responsive image
- Resize the browser or preview to a narrow and a wide viewport.
- Confirm the image stays inside its container and keeps its proportions.
- Check that the mobile crop appears when its media condition matches and that the fallback image still has useful
alttext.
For detailed rules and examples, see MDN's guides to responsive images and the <picture> element.