A simple approach to working with responsive images

The responsive image specification is a fantastic document that describes many uses for such images. But experience tells me that most often when working with them you only need to know how to give the client copies of the same image of different sizes, choosing them depending on the width of the page view area. We call this "resolution switching." To solve this problem, you can use the attributes srcsetand sizes.

The output of responsive images involves the use of fairly complex logic. This, among other things, includes determining which image will be displayed, as well as determining whether the user is working with a high-resolution screen. Fortunately, browsers are better than people who can determine which images are best suited for each particular user. All we need to do is give them some clues. The attribute srcsetgives the browser a list of graphic resources from which it can select the most suitable image. The attribute sizesallows you to tell the browser about what size image you want to show in a particular case.



And by the way, using responsive images you don’t have to worry about browser support for this technology. The attributes we are interested in enjoy excellent browser support. And besides, we have at our disposal a backup mechanism designed for older browsers like IE11.

How the tag "communicates" with the browser


This is how the tag <img>tells the browser which image to select.


"Talk" of the tag and browser

Here the tag<img>tells the browser the following: "With this screen size, I will be displayed in approximately the following size (indicates an attributesizes). You can take any of these images that have the following width (indicates an attributesrcset). Therefore, please choose the image that is now best suited. "

Srcset attribute


The attribute srcsetgives the browser a set of graphic resources from which it can choose the most suitable. It also contains information about the size of each of the proposed images.


Srcset

attribute This attributesrccontains a fallback image for browsers that do not understand the attributesrcset. ThesrcsetURL contains images and information about their width. From the set of images provided to him, the browser will choose what suits best. Moreover, if the user has a display with a high pixel density (Retina display) - the browser will take this into account when choosing an image.

The attributesrcsetcontains a list of image URLs followed by image width information. Pairs areURL-separated by commas. List items look like this:image.jpg 1000w. Such a record tells the browser that the imageimage.jpgis 1000 pixels wide.

Describing the set of images in this way, we tell the browser the following: "I give you a list of images and trust you to choose the most suitable one."

The browser will select the best image, guided by a complex set of criteria, which include what image the user displays, what the current size of the viewing area is, and whether the user has a high-resolution display.

The browser is intelligent enough to know that on a low-resolution desktop display, if the width of the output image is 800 pixels, you need to select the image from the list with a width of at least 800 pixels.

The browser, in addition, knows that if an image with a width of 320 pixels is displayed on a high-resolution display, you need to select an image file that is at least 640 pixels wide. As a result, we do not need to worry about 1x and 2x graphic resources. All you need to do is give the browser a good set of images and let it do its job.

How to describe images suitable for different screens?

Sizes attribute


Attribute srcsetis a great tool. But when the browser reads the HTML code of the page, it does not know whether, for example, it uses the CSS style, which sets the image size to 50% of the screen width. 

This is where the attribute comes into play sizes. With it, we can give the browser a hint about what size the image will be displayed after applying CSS to it.


Sizes attribute

  • 100vw- the default size when none of the conditions is met. It is indicated last in the list that is in the attribute sizes.
  • 1023px - window width.
  • 780px - image width when the specified condition is met.

The browser will stop at the first fulfilled condition.

The attribute sizescontains a list of media conditions, separated by commas. Media conditions are a subset of media queries. Here you cannot specify the type of environment to which the condition ( printor screen) is applicable , but you can use media queries related to the width of the viewing area.

Each list entry contains the width of the viewport window and the corresponding image width. The list item has the form (min-width: 1023px) 780px. Such a record tells the browser that if the width of the viewport is 1023 pixels (or more), then you need to use an image with a width of 780 pixels.

Here, in addition, relative width units can be used. For example, something like50vw. This tells the browser that the width of the image will be 50% of the width of the viewport. Here, in more complex situations, you can even use the function calc. For example, the view design calc(50vw — 2rem)tells the browser that the image width will be 50% of the width of the viewport minus 2rem. Perhaps the width is set this way to take into account the width of some indentation or some border.

The last element of the list is not provided with a media condition. If you add a width to the list and do not specify a media condition, the corresponding value will be considered as the default value, that is, in the event that none of the other conditions is met.

The browser will look at this list from top to bottom and stop at the first suitable element corresponding to the width of the viewport.

Assume the sizesfollowing is in the attribute :

(min-width: 1023px) 780px,
(min-width: 675px) 620px,
100vw

Here is what will happen in different situations:

  • If the user is working on a large desktop display, then the browser will consider the first element of the list suitable and will know that the image should be 780 pixels wide.
  • The standard width of the viewing area of ​​an upright iPad screen is 768 pixels. In this situation, the browser will skip the first entry in the list, but will find that the current conditions match the second entry. It tells the browser that the image will be 620 pixels wide.
  • , sizes. , , 100% .

Of course, these are just examples. In the real world, everything is much more complicated. For example, a user with a large screen viewing a page in a narrow browser window will receive a smaller image than he would have if the window was expanded to full screen. A user with an iPad Pro may well get a larger image if he places the device in landscape mode. If he uses the tablet in portrait mode, he may get a medium-sized image. And if he uses the browser in the mode when the screen is divided between several windows, then he may get a small image. Some phones with large screens will comply with the second rule from our list when working with them in landscape mode. This is the charm of the described system:the developer does not need to take care of all these special cases and the different form factors of the devices. It is enough for him to tell the browser which version of the image to choose for a specific viewing area.

How to prepare a list of images from which the browser will choose the most suitable?

Src attribute


You may have noticed that the attribute is still used in all the examples above src. You might be wondering if this attribute is needed given the attribute srcset. The point here is that if we give the browser an attribute srcset, then if it is a modern browser, it will replace the value srcin the DOM with the value corresponding to the image selected from srcset. As a result, it turns out that modern browsers ignore the attribute src, focusing instead on the attribute srcset.

But the attribute src, in itself, is still important for browsers that do not support working with responsive images. Such browsers, quite old, ignore the srcsetand attributes sizes. They simply do not know about their existence. But attributesrcthey understand, so you can write the address of the image into it, which will serve as a backup option for such browsers. I usually write in this attribute the address of the smallest image that looks good on desktop monitors that do not have a high pixel density.

Questions and answers


▍How to generate image sets?


Images can be generated in various ways: manually, using the tool for creating responsive images, using the appropriate CDN capabilities.

In order to create images manually, you need to open the original image in Photoshop (or in another editor that you use) and export it in all necessary sizes.

This may require a lot of time, so you may want to automate this work using the appropriate tool. Among these tools, I like Responsive Image Breakpoints Generator the most.from Cloudinary. When working with this tool, just transfer the image to it, after which it will automatically create its variants of different sizes. Here you can adjust the number of generated images. Once the images are ready, they can be downloaded and used in the project.

Another option for supporting responsive images is to use the appropriate CDN to host them. For example - Cloudinary or imgix. Using a similar service, the image in the highest resolution available is downloaded to the CDN. You can then request versions of the image in different sizes using the URL parameters. In this case, you do not have to worry about resizing the image: just tell the CDN about the size in which you are going to display the corresponding image.

Here is a list of services and projects that you can use to create variations of images of different sizes.

▍What sizes should I provide to the browser?


Good question! If you give the browser too many graphical resources, then you will simply waste your time and effort creating them. If there are too few resources, this will mean that you are forcing users of your site to download images that are larger than they need.

If you work with a single image and you have the opportunity to customize the layout for the output of this image, then you can use the Responsive Image Breakpoints Generator tool. He will automatically examine the image and decide on what is the optimal set of resources (in terms of balance between file sizes and resolution) generated from this image. Then this tool will not only generate files, but also automatically prepare srcsetand attributes sizes.


A standard set of image sizes with a width of 320 to 2560 pixels.

If you are working in a certain CMS, or if you are creating a web application, and you don’t know what image size will be displayed in one place or another, then I recommend using the standard set of sizes images. Previously, I used the following dimensions:320w,640w,960w,1280w,1920wand2560w. These are round numbers obtained by multiplying 320 by different coefficients. This set of resources covers the needs of a wide variety of screens - from small mobile displays to huge desktop monitors.

However, using a standard set of resources is always less effective than using your own set, taking into account the features of the project. In this case, although we see a quite logical sequence, it shows a progressive increase in file sizes, since if the width (and, correspondingly, height) of an image is doubled, then the number of pixels in this image is quadrupled . As a result, if you have to use a standard set of image sizes, then you might need to choose a set that will have fewer options for images of small sizes and more options for large sizes.

If you host images on Cloudinary, then another approach will be available to you. It is to useCloudinary API , which allows you to process images using Responsive Image Breakpoints Generator when they are downloaded. After the images are automatically processed, you can dynamically populate the srcsetand attributes using the API response sizes.

▍ What values ​​should be entered in the sizes attribute?


In order to figure out what values ​​should be entered in the attribute sizes, you need to analyze the CSS and understand what image width is displayed in different conditions.

Sometimes this is determined by the width of the image itself:

img {
  width 320px;
}

@media screen and (min-width: 37.5em) {
  width: 640px;
}

In this case, there are two fixed image size options. This fact can be directly reflected in the attribute sizes:

<img
  alt="Ferrari"
  src="ferrari.jpg"
  srcset="ferrari-s.jpg 320w,
          ferrari-m.jpg 960w,
          ferrari-l.jpg 1920w"
  sizes="(min-width: 37.5em) 640px, 320px">

However, it often turns out that image sizes are flexible. Often images inherit sizes from their containers:

img {
  height: auto;
  width: 100%;
}

.container {
  padding: 1rem;
  width: 100%;
}

@media screen and (min-width: 37.5em) {
  .container {
    width: 50%;
  }
}

In this example (assuming that the only element affecting the width of the image is .container) the width of the container can be considered the width of the image. Here it is worth paying attention to the fact that the width of the inner indent is subtracted from the width of the container. You may need to consider this, maybe not. It all depends on how much the indentation affects the final width of the image.

<img
  alt="Ferrari"
  src="ferrari.jpg"
  srcset="ferrari-s.jpg 320w,
          ferrari-m.jpg 960w,
          ferrari-l.jpg 1920w"
  sizes="(min-width: 37.5em) calc(50vw - 2rem),
         calc(100vw - 2rem)">

As you can see, setting an attribute is sizeshighly dependent on the particular layout. Usually I build work, starting with researching images in the browser developer tools and figuring out which options affect the size of the images.

▍How to check the correct settings for responsive images?


It's easy to imagine that testing the correct settings for responsive images can be difficult and time-consuming. But, to our happiness, there is a tool that simplifies the solution of such problems. This is a Responsive Image Linter .

This is a bookmarklet that can be added to the browser and used on your own site. When it is called, it automatically scans the page, using various sizes of the viewing area and screen pixel density to test the images.

Then he displays a report containing information about all the images of the page, and whether the management of their sizes is organized correctly. If something goes wrong when testing the page, you will be informed about this and even given advice on how to fix the problem.

Summary


As you can see, the combination of attributes srcsetand sizesprovides a huge opportunity. By setting these two attributes, you tell the browser about the width of the images that you want to use for a certain width of the viewing area, and give a list of graphic resources from which the browser selects the one that it considers most suitable.

If you need to solve more complex problems when working with images, be aware that there are tools for solving such problems. Let's say this is something like using modern graphic formats like WebP , or sending different images to the client, depending on the screen size. If you want to delve into the work with responsive images - take a look at this material.

Dear readers! Do you use responsive images in your projects?


All Articles