w
is the intrinsic width of an image. It's the number you get when you right click the image and select Get Info on Mac, or Properties on Windows.
Why do you need to specify w
? Because the first value of the srcset
attribute only points to the link to load the image. It says nothing about the width of an image. The browser can't tell the dimension of an image until it has actually been loaded.
And why does the browser need to know the intrinsic width of an image?
Here is what browsers do when loading an image:
- look at its device width
- look at
sizes
and figure out which image size will be best to choose
- look at the reference list in
srcSet
and choose the image whose size matches, or is bigger than the number above.
To borrow the sample code from MDN:
<img srcset="elva-fairy-480w.jpg 480w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy">
A common practice is include the intrinsic image width in the image path. However, there is nothing that stops you from lying like this:
<img srcset="elva-fairy-480w.jpg 600w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy">
This means that if a browser with a viewport width of 480px loads the page, the max-width: 600px
condition will be true, and the browser has a slot of 480px wide to load image.
The image elva-fairy-480w.jpg
will be loaded, as its intrinsic width (600w - inflated!) is closest to the slot size.
So there is probably no harm if you overstate the intrinsic width of your image.
What if you understate the intrinsic width?
<img srcset="elva-fairy-480w.jpg 280w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 600px) 480px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy">
On a viewport width of 480px, the image elva-fairy-800w.jpg
will be loaded instead because elva-fairy-480w.jpg
is reported to be 280w and doesn't meet instruction in sizes
.
So understating the intrinsic width of an image will result in the browser loading an overly large image, which defeats the very purpose of responsive iamges.
I haven't thought through all the ramifications from lying about the image's intrinsic width though.