Sub topic 3
Serving sharper images with x descriptors
This chapter assumes you know the img element with its src and alt attributes, and basic CSS. It also assumes you know that a CSS pixel is not always one device pixel. You will learn how srcset with x descriptors lets the browser pick a sharper file on high-density screens, and where this technique stops being enough.
The problem x descriptors solve
A CSS pixel is a unit of layout. A device pixel is a physical dot on the screen. The ratio between them is the device pixel ratio (DPR). On a standard monitor the DPR is 1. On many phones and laptops it is 2 or 3.
Suppose your layout shows an image in a 400 by 300 CSS pixel box. On a DPR 1 screen, that box holds 400 by 300 device pixels, so a 400-pixel-wide file fits exactly. On a DPR 2 screen, the same box holds 800 by 600 device pixels. The 400-pixel file gets stretched across them and looks soft.
You could ship the 800-pixel file to everyone. Then DPR 1 users download roughly four times as many pixels as they can display. The x descriptor lets you offer both files and have the browser choose.
Basic syntax
<img
src="photo-400.jpg"
srcset="photo-400.jpg 1x, photo-800.jpg 2x"
width="400"
height="300"
alt="A lighthouse on a rocky coast at sunset">The srcset attribute holds a comma-separated list of candidates. Each candidate is a URL, whitespace, and a density descriptor. A density descriptor is a number followed directly by x. The 2x here means "use this file when one CSS pixel maps to two device pixels."
Three things work together in this example:
srcsetlists the candidates.srcis the fallback for browsers that ignoresrcset. It also acts as the 1x candidate in browsers that supportsrcset.widthandheightgive the size in CSS pixels. The 800-pixel file is displayed at 400 CSS pixels wide, so it fills 800 device pixels on a 2x screen.
How the browser chooses
With density descriptors, the choice depends on one number, the DPR. The browser compares it with the candidates' descriptors.
flowchart TDThe block above is only a placeholder name. The real diagram follows.
The HTML specification leaves the final decision to the browser. In practice, browsers choose the smallest candidate whose density is at least the current DPR. They take the largest candidate if none is high enough. This table shows typical results for the example above.
| Device pixel ratio | File chosen | Reason |
|---|---|---|
| 1 | photo-400.jpg | Exact match with 1x |
| 1.5 | photo-800.jpg | Nearest higher density |
| 2 | photo-800.jpg | Exact match with 2x |
| 3 | photo-800.jpg | No higher candidate, so the largest is used |
Picking a higher density than needed keeps the image sharp. Picking a lower one would force the browser to enlarge it.
Rules for the descriptor list
- A candidate with no descriptor counts as
1x. These two are equivalent:photo.jpgandphoto.jpg 1x. - Fractional values are valid, for example
1.5x. - Each density may appear only once in a list. Two
2xcandidates make the list invalid. - Write the number and the
xwith no space between them:2x, not2 x. - Do not mix
xandwdescriptors in onesrcset. Thewform is covered in the next chapter. - The
sizesattribute has no effect on asrcsetthat usesxdescriptors. Leave it out.
A candidate list that breaks these rules is not partially applied. The browser can discard it and use src alone, so you will see 1x behavior with no error message.
Why a 2x file is not "twice as big"
A 2x file has twice the width and twice the height. That is four times the pixels. Compressed file size does not grow by exactly four, but it grows by a lot. A 3x file has nine times the pixels of the 1x file.
This has two practical results:
- Offering 1x and 2x covers most screens. A 3x candidate often adds a lot of bytes for a small visual gain, especially for photographs.
- High-density files can use stronger compression. Detail is packed more tightly at 2x, so quality loss is harder to see. A JPEG quality of 60 to 70 at 2x can look as good as a quality of 80 at 1x.
Never create a 2x candidate by upscaling the 1x file. The file would be larger and look no sharper. Always resize from the original.
Making the files
If you have a 1600-pixel original, resize it to the two widths you need. This uses the ImageMagick 7 command.
magick photo.jpg -resize "400x" photo-400.jpg
magick photo.jpg -resize "800x" photo-800.jpgThe 400x geometry means a width of 400 pixels with the height scaled to keep the aspect ratio. A later chapter covers generating many variants.
When x descriptors fit and when they do not
Density descriptors assume that the image displays at the same CSS size regardless of the viewport. That is true for:
- logos in a header
- avatars and thumbnails with a fixed size
- icons and badges
- product images in a fixed-width card
It is not true for an image that fills a fluid column or the full viewport width. If the box is 300 CSS pixels wide on a phone and 900 on a desktop, a 1x/2x list cannot express that. A phone with DPR 3 would download the 2x file, which may be sized for the desktop layout, and a DPR 1 desktop would get the 1x file at the wrong size. Fluid layouts need w descriptors and sizes, which the next chapters cover.
Zoom and window changes
Browser zoom changes the DPR the page sees. At 200 percent zoom on a DPR 1 monitor, window.devicePixelRatio reports 2, and the browser may select the 2x candidate. Two behaviors are worth knowing:
- Browsers can re-run selection when the DPR changes, for example when you drag a window to a second monitor with a different density.
- Browsers are not required to swap to a smaller file after they have loaded a larger one. If you zoom in and then out, the larger image may stay.
Both matter when you test. Reload the page after changing zoom or monitors if you want a clean result.
Checking which file loaded
The currentSrc property of an image element holds the URL the browser selected. Compare it with devicePixelRatio. This version waits for the image to finish loading, so currentSrc is populated and naturalWidth is known.
const img = document.querySelector('img');
function report() {
console.log('Selected:', img.currentSrc);
console.log('Device pixel ratio:', window.devicePixelRatio);
console.log('File width in pixels:', img.naturalWidth);
console.log('Displayed width in CSS pixels:', img.clientWidth);
}
if (img.complete) {
report();
} else {
img.addEventListener('load', report);
}For a healthy 2x result, naturalWidth should be about clientWidth multiplied by the DPR. If a DPR 2 screen shows naturalWidth of 400 with a clientWidth of 400, the browser picked the 1x file. The browser's Network panel gives the same answer from the transfer side.
Common errors
- A missing
widthandheight. Without them, the browser may lay out the image at the chosen file's natural size, so a 2x file appears at 800 CSS pixels wide. Set the attributes to the 1x size. This also reserves space, as a later chapter explains. - A
srcthat points to the 2x file. The fallback then sends the large file to every browser that ignoressrcset. Pointsrcto the 1x file. - A different crop in each file. If the 2x file shows a different part of the scene, users see the image jump as the DPR changes. Use
picturefor deliberate crops. - A wrong descriptor syntax.
photo-800.jpg 2andphoto-800.jpg @2xare invalid. Only2xworks. - Testing in one browser window only. An image that looks fine on your 2x laptop proves nothing about 1x users. Check both, using zoom or the device toolbar in developer tools.
Exercise
A page shows a 120 by 120 CSS pixel avatar. You have avatar-120.png, avatar-240.png, and avatar-360.png. Write the img element so that DPR 1 screens get the smallest file and DPR 2 and DPR 3 screens each get a matching file. What file does a screen with DPR 1.5 most likely load?
Show answer
<img src="avatar-120.png" srcset="avatar-120.png 1x, avatar-240.png 2x, avatar-360.png 3x" width="120" height="120" alt="Profile photo of the account owner"> A DPR 1.5 screen most likely loads avatar-240.png, the nearest candidate with a density at or above 1.5.
Exercise
On a DPR 2 screen, img.clientWidth is 400 and img.naturalWidth is 400, although the srcset has a 2x candidate. Name two likely causes.
Show answer
The srcset may be invalid (for example a duplicate density, a space in "2 x", or mixed x and w descriptors), so the browser used src alone. The page may also have been loaded before the DPR changed (zoom or a monitor switch) and not reloaded, so the browser kept the earlier file.