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.
Previous
What are CSS preprocessors (Sass/Less) and what do they add?
Next
What is the CSS outline property and how does it differ from border?
More HTML / CSS Questions
View all →- Intermediate How does the CSS cascade work?
- Intermediate What is BEM (Block Element Modifier) methodology in CSS?
- Intermediate What are CSS custom properties (CSS variables)?
- Intermediate What is the difference between em, rem, px, vh, and vw units in CSS?
- Intermediate How does Flexbox differ from CSS Grid? When would you use each?