The HTML srcset attribute provides the browser with a set of multiple image sources so that it can select the best one for the device.
Definition and Usage
➔ The srcset attribute allows the browser to choose the most appropriate image based on the capabilities of the user's device (screen size, pixel density, network conditions, etc.).
➔ The srcset attribute can be used on the <img> and <source> elements.
Syntax
//Changes the image based on pixel density.
//1x: a standard-density display image.
//2x: a double-density display image
<img src="image-1x.jpg" srcset="standard-density-image.jpg 1x, double-density-image.jpg 2x" alt="Image description">
//OR
//Changes the image based on screen widths.
//secset Specifies the actual width of the image.
//sizes tells the browser to select the best image to display under different media conditions.
<img src="default-image.jpg" srcset="image-600w.jpg 500w, image-800w.jpg 800w, image-1200w.jpg 1200w"
sizes="(max-width: 600px) 500px, (max-width: 1024px) 800px, 1200px" alt="Responsive image">
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML srcset element example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML srcset element example</h3>
<p>Resize the browser window to load different sizes of an image.</p>
<img src="./resources/images/workplace2.png"
srcset="./resources/images/workplace2.png 480w, ./resources/images/workplace2.png 800w, ./resources/images/workplace2.png 1200w"
sizes="(max-width: 480px) 480px, (max-width: 800px) 800px, 1200px" alt="Responsive image">
</body>
</html>
Click on the "Try it Now" button to see how it works.