How to Use srcset in HTML for Responsive Images
Use the
srcset attribute inside an <img> tag to provide multiple image sources for different screen sizes or resolutions. The browser picks the best image based on device width or pixel density, improving loading speed and display quality.Syntax
The srcset attribute lists image files with descriptors that tell the browser when to use each image. It works with src as a fallback.
- Image URL: The path to the image file.
- Descriptor: Defines when to use the image, either with
w(width in pixels) orx(pixel density).
Example: srcset="image-400w.jpg 400w, image-800w.jpg 800w" means use the 400px wide image for smaller screens and 800px for larger.
html
<img src="image-default.jpg" srcset="image-400w.jpg 400w, image-800w.jpg 800w" alt="Example image">
Output
An image displayed using the best source based on screen size.
Example
This example shows how to use srcset with width descriptors to serve different images for different screen widths. The browser picks the best image automatically.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Srcset Example</title> </head> <body> <h1>Responsive Image with srcset</h1> <img src="small.jpg" srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w" sizes="(max-width: 600px) 400px, (max-width: 900px) 800px, 1200px" alt="A scenic view"> </body> </html>
Output
A scenic view image that changes source based on screen width.
Common Pitfalls
- Not including a fallback
srcimage can cause no image to show in unsupported browsers. - Using incorrect descriptors (mixing
wandximproperly) confuses the browser. - Forgetting the
sizesattribute when using width descriptors can lead to wrong image selection. - Not providing meaningful
alttext hurts accessibility.
html
<!-- Wrong: missing src fallback and sizes --> <img srcset="small.jpg 400w, large.jpg 800w" alt="Wrong example"> <!-- Right: includes src and sizes --> <img src="small.jpg" srcset="small.jpg 400w, large.jpg 800w" sizes="(max-width: 600px) 400px, 800px" alt="Right example">
Output
First image may not show in some browsers; second image works correctly.
Quick Reference
Remember these tips when using srcset:
- Always include a
srcfallback image. - Use
wdescriptors for responsive widths orxfor pixel density. - Use the
sizesattribute withwdescriptors to tell the browser the image display size. - Provide descriptive
alttext for accessibility.
Key Takeaways
Use
srcset with src to provide multiple image options for different devices.Include the
sizes attribute when using width descriptors to guide the browser's choice.Always provide meaningful
alt text for accessibility.Avoid mixing width (
w) and pixel density (x) descriptors incorrectly.Test images on different screen sizes to ensure correct loading.