What is the srcset
Attribute in the <img>
Tag and How is it Used?
The srcset
attribute in the <img>
tag is used to specify multiple image sources for an image, allowing the browser to select the best option depending on the screen size and resolution. This is particularly useful in responsive design, where you need to serve different images for different devices to optimize loading times and performance.
Key Concepts:
- Resolution Switching: It allows the browser to choose between images with different resolutions. If you're designing for devices with various screen densities,
srcset
helps by serving the appropriate image based on the device's characteristics. - Art Direction: You can specify different images for different conditions, such as aspect ratio changes.
Example Usage:
<img src="small.jpg" srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w" alt="A beautiful landscape">
In this example, the browser will choose the image based on the current viewport width:
small.jpg
will be used for viewports up to 500 pixels wide.medium.jpg
will be used for viewports up to 1000 pixels wide.large.jpg
will be used for viewports up to 1500 pixels wide.
How it Works:
The srcset
attribute works in conjunction with the sizes
attribute (optional) to give the browser hints on how to select the best image. The sizes
attribute specifies the layout size for the image, allowing the browser to decide which image to choose from the srcset
list.
Example with sizes
:
<img src="default.jpg" srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w" sizes="(max-width: 600px) 480px, (max-width: 1200px) 800px, 1200px" alt="Responsive example">
In this case, the browser uses the sizes
attribute to decide which image to load:
- For viewports up to 600px wide, it picks
small.jpg
. - For viewports up to 1200px wide, it picks
medium.jpg
. - For wider viewports, it loads
large.jpg
.
Conclusion:
Using srcset
effectively can improve the performance of your website on different devices by ensuring each user receives the most suitable image for their device, enhancing the user experience and reducing unnecessary data usage.