Responsive Images
This guide teaches you how to make images responsive without using any library.
Users access your website from any device, and you want to ensure they get the best-quality images while not wasting bandwidth. You want mobile users to get smaller images and desktop users to get higher-resolution images. The <img> tag has srcset and sizes attributes, which are super helpful for delivering responsive images to end users.
Here is an example:
<img
alt="image alt text"
src="medium.jpg"
srcset="
small.jpg 240w,
medium.jpg 300w,
large.jpg 720w
"
sizes="
(min-width: 960px) 720px,
100vw
"
>
Let us walk through each part.
alt="image alt text"
As with each <img> tag, you just use the alt text.
src="medium.jpg"
The familiar way to specify the location of your image. Browsers that do not support srcset and sizes will fall back to src.
srcset="small.jpg 240w, medium.jpg 300w, large.jpg 720w"
This is where the magic begins. With scrset you specify a list of images in different sizes. In this example, we have three sizes of the same image. Behind the file name of each image, you specify the width in pixels (w for width). For example, small.jpg 240w means that this image is 240px wide.
sizes="(min-width: 960px) 540px, 100vw"
With sizes, you specify the image size and when it must be displayed. This is done with a combination of a media query and the image width. This is the most powerful one.
The above code for sizes does the following:
- if viewport width is 960px or greater, show the image with a width of 540px,
- if the viewport width is smaller than 960px, then show the image as wide as the viewport (100vw means 100% of the viewport width).
Now you may notice that in our example of srcset there’s no image with a width of 540px. That’s not a problem. The browser will select the best image available that's larger. In this case, it will use large.jpg at 720px wide.
How Gumlet helps here
You can see the biggest part here is not writing the HTML code, but you will notice you need to generate three different images small.jpg, medium.jpg and large.jpg. Doing that is tough and time-consuming. You also need to figure out storage for those 3 images. Here is how Gumlet can solve it:
With Gumlet, you just pass URL parameters for different sizes, and Gumlet generates those images on the fly.
<img
alt="image alt text"
src="https://demo.gumlet.io/sea.jpeg?w=500"
srcset="
https://demo.gumlet.io/sea.jpeg?w=240 240w,
https://demo.gumlet.io/sea.jpeg?w=300 300w,
https://demo.gumlet.io/sea.jpeg?w=720 720w
"
sizes="
(min-width: 960px) 720px,
100vw
"
>
This way, you can serve images of different sizes to different screen sizes without using any JavaScript or maintaining any complex infrastructure for image processing.

