HTML srcset Attribute
Description
The srcset
attribute in HTML is used with <img>
elements to provide a list of image sources for the browser to choose from based on the display characteristics of the device, such as its pixel density (e.g., Retina displays) and the size of the image's display area. This allows developers to ensure that images are served in appropriate resolutions, enhancing the user experience by making images look sharp on high-resolution displays while also optimizing loading times and bandwidth usage for lower-resolution displays.
The srcset
attribute can specify multiple image files by listing them with their respective sizes or pixel density descriptors. For instance, you can define images to be used for 1x, 2x, and 3x pixel density displays, or you can specify different images for different viewport widths using the sizes
attribute in conjunction with srcset
to further guide the browser in selecting the most appropriate image.
When using srcset
, the browser automatically selects the most suitable image source from the list based on the current device's capabilities and the conditions specified by the developer. This selection process is seamless to the user and occurs without the need for any custom JavaScript, making srcset
a powerful tool for building responsive, high-performance web applications.
An example usage of the srcset
attribute might look like this:
<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="An example image">
In this example, small.jpg
is the fallback image for browsers that do not support srcset
. The srcset
attribute provides two additional images: medium.jpg
for displays or conditions up to 1000 pixels wide, and large.jpg
for displays or conditions up to 2000 pixels wide. The browser selects the most appropriate image based on the current display characteristics.
Syntax
<tagname srcset="URL width">
Values
- URL widthThe URL or path of the image file, followed by the actual image width. Image width is measured in pixels but using the w unit. (e.g. 200w is 200px).
Applies To
The srcset
attribute can be used on the following html elements.
Example
<img
src="images/sunset1.jpg"
srcset="images/sunset480.jpg 480w, images/sunset768.jpg 768w, images/sunset1024.jpg 1024w"
sizes="(max-width: 480px) 480px, (max-width: 768px) 768px, 1024px"
alt="Responsive image"
/>
Browser Support
The following table will show you the current browser support for the HTML srcset
Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 29th March 2024