For small viewports, we may want to show a variation of the desktop image. A very common use case of this is a cropped, smaller version of the desktop image. In this lesson, we are going to discuss showing a cropped version of the desktop image, but only for smaller viewports.
Instructor: [00:00] Over here in the browser, we have an image, which is 1,024 pixels wide. This is suitable for desktop devices, but not particularly suitable for smaller devices because of its dimensions and the fact that it has quite a lot of space around it. A lot of the room will be taken up by the grass.
[00:42] What we need to do first is wrap the image in a picture tag. As the first element in the picture tag we can supply a source. To the source we're going to provide a media attribute, and that's going to be a media query. Let's say max width, 500 pixels.
[01:06] The next attribute we're going to apply is the source set attribute. Inside the source set attribute we're going to pass the image that we want to load when the viewport size is 500 pixels or less.
[01:22] I'm going to grab that image now. Let's save and refresh and see how that affects our page. Let's open the dev tools to see the width. As we go down below 500 pixels, we get the cropped version of the image.
[01:40] This way we can fine-tune which variations of desktop images get shown on smaller viewports. If we wanted to supply more than one variation of the image, we could supply more source elements.
[01:55] Loading images in this way will mean that our users don't use as much of their bandwidth as they would loading a larger image. It gives them an improved user experience, because the images are optimized for smaller screens.
[02:10] This approach is different to resolution switching, because it allows us to have fine-tuning over which exact image gets loaded depending on the viewport width.