Responsive Images with srcset
Uses srcset and sizes attributes to serve appropriately sized images based on viewport, plus art direction with the picture element.
Code
<!-- Responsive image with srcset -->
<img
src="image-800w.jpg"
srcset="image-400w.jpg 400w,
image-800w.jpg 800w,
image-1200w.jpg 1200w,
image-1600w.jpg 1600w"
sizes="(max-width: 600px) 400px,
(max-width: 1200px) 800px,
1200px"
alt="A descriptive alt text"
loading="lazy"
decoding="async"
width="800"
height="600">
<!-- Art direction with picture element -->
<picture>
<source
media="(max-width: 768px)"
srcset="mobile-image.jpg"
type="image/jpeg">
<source
media="(max-width: 1200px)"
srcset="tablet-image.jpg"
type="image/jpeg">
<source
srcset="desktop-image.webp"
type="image/webp">
<img src="desktop-image.jpg" alt="Descriptive text">
</picture>
<!-- High-DPI display support -->
<img
src="logo.png"
srcset="logo.png 1x, [email protected] 2x, [email protected] 3x"
alt="Company Logo">srcset with sizes lets the browser choose the optimal image based on viewport and display density, reducing bandwidth. The <picture> element enables art direction (different images for different screens) and format negotiation (WebP with JPEG fallback). loading="lazy" defers offscreen images. Always specify width and height to prevent layout shift.
Interactive Tools for This Topic
Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.Viewport Unit CalculatorConvert between pixels and the CSS viewport units vw, vh, vmin, and vmax for a given viewport size, in either direction.
Report a problem with this exampleOpens a pre-filled issue on GitHub.