Why you would use a `srcset` attribute in an image tag?
Explain the process the browser uses when evaluating the content of this attribute.TL;DR
srcset gives the browser multiple image candidates so it can choose an appropriate resource for the image's rendered size and device pixel density. With width descriptors such as 480w, also provide sizes so the browser can estimate the image's layout width before final layout is known. The selection is a browser decision and may consider network or cache state, so code should not depend on one exact candidate being chosen.
<imgsrc="/images/hero-800.jpg"srcset="/images/hero-480.jpg 480w,/images/hero-800.jpg 800w,/images/hero-1600.jpg 1600w"sizes="(max-width: 600px) 100vw, 800px"width="800"height="450"alt="Team members collaborating around a table" />
Why you would use a srcset attribute in an image tag?
Responsive images avoid downloading more pixels than the layout can use while still providing enough detail for high-density displays.
Width descriptors and sizes
In the example above, each w descriptor states the file's intrinsic width. Before fetching an image, the browser approximately:
- Evaluates the first matching condition in
sizesto determine the image's slot width in CSS pixels. - Combines that slot width with device pixel density and other implementation factors.
- Selects a suitable candidate from
srcset. - Uses
srcas the fallback whensrcsetis unsupported.
The browser is allowed to use its own selection heuristics, so it may reuse a cached image or choose a different candidate under constrained conditions. The descriptors must match the files' real intrinsic widths. Without sizes, a width-descriptor source set defaults to assuming a 100vw slot, which often downloads an unnecessarily large image.
Pixel-density descriptors
If the image always renders at one fixed CSS size, density descriptors can provide resolution variants:
<imgsrc="/icons/logo.png"srcset="/icons/logo.png 1x, /icons/logo@2x.png 2x"width="160"height="40"alt="Example Company" />
Do not mix w and x descriptors in the same srcset.
Art direction uses <picture>
srcset normally offers different resolutions of the same image. When narrow screens need a different crop or composition, use <picture> with <source media> and keep an <img> fallback. The <img> still owns the alternative text and intrinsic dimensions.
Always provide meaningful alt text when the image conveys content and alt="" when it is decorative. Set width and height or an equivalent aspect ratio to reserve layout space. Lazy-load below-the-fold images, but do not lazy-load the likely Largest Contentful Paint image.