In this blog post, we will discuss how to use the HTML img
tag’s srcset
attribute to define responsive images. This technique allows the browser to download and display images based on factors like pixel density and window width, optimizing the page loading speed and user experience.
To use the srcset
attribute, you need to provide multiple image sources for different screen sizes. Here’s an example:
<img src="dog.png"
alt="A picture of a dog"
srcset="dog-500.png 500w,
dog-800.png 800w,
dog-1000.png 1000w,
dog-1400.png 1400w">
In the above example, we have specified four additional images for four different screen sizes. Each image is followed by its width designation (e.g., 500w
, 800w
, etc.).
To establish a relationship between the image size and the viewport, you also need to use the sizes
attribute. Here’s an updated example:
<img src="dog.png"
alt="A picture of a dog"
sizes="(max-width: 500px) 100vw, (max-width: 900px) 50vw, 800px"
srcset="dog-500.png 500w,
dog-800.png 800w,
dog-1000.png 1000w,
dog-1400.png 1400w">
In this updated example, the sizes
attribute specifies the image size in relation to the viewport. It is defined using multiple conditions separated by commas. For example, (max-width: 500px) 100vw
means that if the window size is less than 500px, the image will be displayed at 100% of the window width.
Similarly, (max-width: 900px) 50vw
specifies that if the window size is greater than 500px but less than 900px, the image will be displayed at 50% of the window width. And 800px
sets the image size to 800px if the window size is larger than 900px.
The unit of measure used here is vw
, which refers to a percentage of the window width. For example, 100vw
represents 100% of the window width.
To generate the srcset
attribute and progressively smaller images, you can use a helpful website like responsivebreakpoints.com.
Overall, using the srcset
attribute and defining responsive images is a great way to optimize your website for different devices and screen sizes.