Responsive Images and srcset Basics
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Why One Image Size Is Not Enough
Sending the same large image to every device wastes bandwidth on small phone screens that will only ever display it small - and can look blurry when stretched on a very large or high-density display if the image was sized too small.
Using srcset to Offer Multiple Sizes
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="A description of the photo">Each entry in srcset lists an image file alongside its actual pixel width (the w descriptor). The browser then picks whichever file best matches the space it needs to fill, based on the sizes hint.
What the sizes Attribute Is For
sizes tells the browser how much of the viewport the image will actually occupy at different widths - it does not choose an image file by itself, but gives the browser the information it needs to make the right choice from srcset.
In the example above: below 600px viewport width, the image will span the full viewport (100vw); above that, it will only take up half the viewport (50vw).
Why the Plain src Still Matters
The plain src attribute acts as a fallback for browsers that do not understand srcset, so it should always be included alongside it, typically pointing at a reasonably sized middle-ground image.
The Practical Payoff
A phone on a slow connection can download a small 400px image instead of an unnecessarily large 1200px version meant for a desktop layout, directly improving load time without any change to the visual design.