Width and density descriptors
Understanding width (w) and density (x) descriptors in srcset. Use examples and use Markdown.
srcsetis an HTML attribute that allows developers to provide multiple image sources with different resolutions or pixel densities, and let the browser select the appropriate image based on the device’s display characteristics. Thesrcsetattribute uses a combination of theURLandworxdescriptors to specify the images.
Width (w) Descriptor
The
wdescriptor is used to specify the width of an image in pixels. It is used when we want to provide the browser with the dimensions of an image so that it can choose the appropriate image for the available screen space.
The syntax for using the
wdescriptor insrcsetis as follows:
<img src="small.jpg"
srcset="small.jpg 500w,
medium.jpg 1000w,
large.jpg 2000w"
alt="Example Image">
In the example above, we have provided the browser with three images and their corresponding widths in pixels. The browser will select the image with the closest width to the available screen space.
Density (x) Descriptor
The
xdescriptor is used to specify the pixel density of an image, which is the ratio of physical pixels to CSS pixels. It is used when we want to provide the browser with different versions of the same image with different pixel densities.
The syntax for using the
xdescriptor insrcsetis as follows:
<img src="small.jpg"
srcset="small.jpg 1x,
medium.jpg 2x,
large.jpg 3x"
alt="Example Image">
In the example above, we have provided the browser with three images and their corresponding pixel densities. The browser will select the image with the closest pixel density to the device’s screen.
Note that the
wandxdescriptors can be used together in the samesrcsetattribute to provide the browser with more options to choose from.