Srcset is an HTML attribute used in the <img> tag to provide multiple image sources for different screen resolutions or viewport sizes.
This attribute enhances the responsiveness of a website, ensuring that the best-suited image is displayed based on the user’s device or browser window size, which improves page load times and overall user experience.
To use the “srcset” attribute, you need to include it in the <img> tag, along with the “sizes” attribute, which defines the width of the image for different viewport sizes. Here’s a code example:
<img src="default-image.jpg" srcset="small-image.jpg 480w, medium-image.jpg 768w, large-image.jpg 1024w" sizes="(max-width: 480px) 480px, (max-width: 768px) 768px, 1024px" alt="An example image">
In this example, there are three different image sources provided in the “srcset” attribute:
- “small-image.jpg” for screens with a width of up to 480 pixels (480w)
- “medium-image.jpg” for screens with a width of up to 768 pixels (768w)
- “large-image.jpg” for screens with a width of up to 1024 pixels (1024w)
The “sizes” attribute defines the conditions under which each image source will be used:
- If the screen width is up to 480 pixels, the “small-image.jpg” will be displayed.
- If the screen width is up to 768 pixels, the “medium-image.jpg” will be displayed.
- For screen widths larger than 768 pixels, the “large-image.jpg” will be displayed.
The “src” attribute with “default-image.jpg” serves as a fallback for browsers that do not support the “srcset” attribute.
For a more in-depth understanding of the “srcset” attribute and how to use it, refer to the MDN Web Docs guide on responsive images (https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images).