🎨 HTML / CSS Intermediate

What are srcset and sizes attributes for responsive images?

Answer

The srcset and sizes attributes on <img> allow the browser to choose the most appropriate image version based on the device's screen resolution and viewport size, saving bandwidth. srcset lists available image files with their widths: srcset="img-400.jpg 400w, img-800.jpg 800w, img-1200.jpg 1200w". sizes tells the browser how wide the image will actually be at different viewport widths: sizes="(max-width: 600px) 100vw, 50vw". The browser calculates which image from the srcset is the smallest one that still looks sharp for the current viewport and DPI. This is critical for mobile performance — serving a 1200px image to a 400px screen wastes data.