Middle+
How to implement the connection of different formats and sizes of images for screens with different pixel densities in HTML? What is the picture tag and the srcset attribute?
sobes.tech AI
Answer from AI
For responsive image loading in HTML, the srcset attribute and the <picture> tag are used to load different formats and sizes depending on the device and pixel density.
- The
srcsetattribute allows specifying multiple versions of the same image with different resolutions or sizes. The browser will choose the most appropriate version based on the screen's pixel density (e.g., 1x, 2x) or viewport size.
Example of using srcset:
<img src="image-1x.jpg" srcset="image-2x.jpg 2x, image-3x.jpg 3x" alt="Example">
Here, the browser will load image-2x.jpg for screens with 2x density, image-3x.jpg for 3x, and so on.
- The
<picture>tag extends capabilities by allowing different images not only based on pixel density but also on media query conditions or file formats. Inside<picture>, multiple<source>elements can be used withmediaandtypeattributes.
Example:
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Example">
</picture>
Here, the browser will first try to load WebP, and if supported, it will use it; otherwise, it falls back to JPEG.
Thus, srcset and <picture> help optimize image loading for different devices, improving performance and display quality.