This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Show Different Variations of Images Depending on the Viewport Width using Art Direction

    Rory SmithRory Smith

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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:22 Let's say we wanted more of the room to be taken up by the sheep. Therefore we want to show a cropped version of this image. There's a way to do this in HTML, which means we can target which image shows before we even get to the CSS or the JavaScript loading.

    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.

    Discuss

    Discuss