Responsive Images in HTML Using srcset
The srcset
attribute is the modern solution for serving different image sizes based on the user's device. Instead of loading unnecessarily large images on mobile devices, srcset
lets the browser choose the most appropriate image size, optimizing for performance and bandwidth usage.
Here's what it looks like:
<img src="image-800w.jpg" srcset="image-400w.jpg 400w, image-800w.jpg 800w, image-1200w.jpg 1200w" sizes="(max-width: 400px) 100vw, (max-width: 800px) 80vw, 1200px" alt="A responsive image" >
Let's break down each attribute:
srcset
: Lists your image versions with their actual pixel widths. Each image size should be compressed appropriately. The format isfilename widthDescriptor
.
For example, image-400w.jpg 400w
means this image is 400 pixels wide. The naming of the file isn't mandatory but best practice. It makes working with responsive images more intuitive when the filename is appropriate.
sizes
: Tells the browser how wide the image will be displayed. The format ismediaCondition imageWidth
. For example,(max-width: 400px) 100vw
means the image takes 100% of the viewport width on screens up to 400px.src
: Fallback image for browsers that don't support srcset. Always include asrc
attribute as a fallback.
Recommended Breakpoints
You can include any breakpoints that make sense for you, but for most websites, these image widths work well:
- 400px (mobile)
- 800px (tablet)
- 1200px (desktop)
Another Example
Just for clarity and so you can see another example before finishing:
<img src="cat-800w.jpg" srcset="cat-400w.jpg 400w, cat-800w.jpg 800w, cat-1200w.jpg 1200w" sizes="(max-width: 400px) 100vw, (max-width: 800px) 80vw, 1200px" alt="A fluffy cat" >
Try it on your projects to give a little performance boost. 🚀