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 best quality images while not wasting bandwidth. You want mobile user to get smaller image and desktop user to get bigger resolution image. 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 fallback 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 the image 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 of width). For example, small.jpg 240w means that this image is 240px wide.
sizes="(min-width: 960px) 540px, 100vw"
With sizes you specify the size of the image and in which situation it must be displayed. This is done by a combination of a media query and the width of the image. This is the most powerful one.
The above code for sizes does the following:
- if viewport width equals to 960px or greater than show the image with a width of 540px,
- if the viewport width is smaller than 960px than 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 upwards in size. In this case, large.jpg will be used with a width of 720px.
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:
When you use Gumlet, you just need to pass URL parameters for different sizes and Gumlet will generate those images on-the-fly for you.
<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 size to different screen sizes without using any Javascript or maintaining any complex infrastructure for image processing.
Updated 2 days ago
