srcset and sizes: Responsive Images in HTML

Give the browser a menu of images with `srcset` and tell it how much screen space the image will take with `sizes`. The browser then picks the most efficient option for the user's device. The footgun is forgetting `sizes`, which makes the browser assume 100vw.
WHY IT EXISTS: Serving a single, large image to all users is inefficient. Mobile users on slow networks waste bandwidth downloading a huge desktop-sized image, while users on high-resolution screens might see a small image stretched and pixelated. We need a way to serve the right image to the right device.
THE MENTAL MODEL: Think of srcset and sizes as a contract with the browser. You provide a 'menu' of available image files and their actual widths (srcset). Then, you provide a 'guide' on how much space the image will occupy on the screen at different viewport widths (sizes). The browser uses both pieces of information to intelligently select and download the most appropriate image from your menu.
HOW IT WORKS: The srcset attribute contains a comma-separated list of image URLs, each followed by a width descriptor (e.g., image-400w.jpg 400w, image-800w.jpg 800w). The sizes attribute contains a comma-separated list of media conditions and the width the image will occupy when that condition is true (e.g., (max-width: 600px) 100vw, 50vw). The browser evaluates sizes first to determine the image's required display width, then looks at srcset to find the smallest image that is at least that width, accounting for device pixel ratio.
WHEN TO USE IT: Use srcset and sizes for any image where the rendered size changes based on the viewport, like full-width banners or responsive content images. This is the standard way to handle resolution switching, where you're serving the same image composition at different sizes to save bandwidth and prevent pixelation.
WHEN NOT TO USE IT: For images that are always a fixed size (like icons), a simple src is sufficient. For 'art direction'—where you need to show a completely different crop or composition on mobile vs. desktop—use the <picture> element with <source> tags, which gives you more explicit control over which image is shown.
ONE CANONICAL EXAMPLE: <img src="fallback.jpg" srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1600w" sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 800px"> This tells the browser: On screens up to 600px wide, the image takes up the full viewport width. Between 601px and 1200px, it takes up half the viewport width. Above 1200px, it's 800px wide. The browser then picks the best file from srcset to fill that space.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.