Image quality can be represented as:
- Based on pixel density: select the highest image quality based on its pixel density. Here is where we use the display density descriptors:
- Based of viewport width: select the highest image quality based on its width (similar measurement than pixels). Here is where we use the width descriptors:
<img src="cat.jpg" alt="cat" srcset="cat.jpg, cat-2X.jpg 2x">
The browser will select the appropriate image according to the resolution of the image (how many pixels are needed to represent the image) (not the size of the viewport).
Using the pixel density method is recommended when the size of the image will not change (like a logo).
<img src="cat.jpg" alt="cat"
srcset="cat-160.jpg 160w, cat-320.jpg 320w, cat-640.jpg 640w, cat-1280.jpg 1280w">
The browser will select the appropriate image according to the width of the image (not the size of the viewport). This is similar to the display density descriptor method. Width descriptors are looking for the resolution of the source file. In other words, if you open the image in an image editor, what does it say the resolution is? Grab the width and put it in the srcset attribute. The browser is the one that chooses the right image for the size of the screen/viewport.
What the browser is doing is comparing the width of the image with the width of the viewport (divides the pixels of the image width by the pixels of the viewport width), and compares the result with the pixel density of the screen (1x, 2x, 3x, etc.). If the result of the division is higher than the screen pixel density, it uses that image. https://www.youtube.com/watch?v=2QYpkrX2N48
Image size can be represented as:
Going further, apart from the image resolution based on viewport size, we can specify the image size based on the viewport percentage that the image is taking.
- Sizes:
<img src="cat.jpg" alt="cat"
srcset="cat-160.jpg 160w,
cat-320.jpg 320w,
cat-640.jpg 640w,
cat-1280.jpg 1280w"
sizes="(max-width: 480px) 100vw,
(max-width: 900px) 33vw,
254px">
The sizes attribute is required any time you use srcset width descriptors. Specifying sizes indicates to the browser how much percentage of the viewport an image must take, hence obtaining the actual width of the image. For a viewport of less or equals to 480px wide, the image will take 100% of the viewport width. For a viewport width of over 900px, the images will be fixed to 254px (they will not grow/shrink as the view port changes).
Note: The browser will also select the right image resolution for the percentage of the viewport that the image is occupying.