Imad
Imad

Reputation: 189

Handling responsive images with img srcset

I'm using angular with material and using img srcset to handle responsive image for header.

This is what I'm doing so far:

<img srcset="../../assets/mtn-bg_600.jpg 600w,
      ../../assets/mtn-bg_960.jpg 960w,
      ../../assets/mtn-bg_1280.jpg 1280w,
      ../../assets/mtn-bg_1600.jpg 1600w"
 sizes="100vw"
 src="../../assets/mtn-bg_1600.jpg" alt="Header image">

I'm confused about how to handle high resolution images with srcset. I have seen examples of srcset only having images with resolution like 1x 2x or with media queries. But want to be clear how can I handle images for high resolutions along with media queries.

Do I need to add high resolution images with their sizes as well in the srcset and img element will automatically handle it.

I'm using default breakpoints that flex-layout for material provides for my application as well as for srcset. Please also suggest if I would need to consider any other breakpoints for srcset.

Thanks!

Upvotes: 3

Views: 3410

Answers (1)

Riley Thornton
Riley Thornton

Reputation: 21

For an in depth look into srcset and responsive images, the MDN web doc "Responsive Images" is a great resource. And there are several other articles out there just a short search away.

Using x-descriptors makes it convenient to serve images at consistent physical sizes on screens of different screen resolutions.

For example, if you have a 900 pixel wide photo loading on a standard screen, you will want a 1350px wide photo loading on a 1.5x screen, 1800px wide on 2x etc, in order for them to look physically the same to the viewer.

The code will look something like this:

<img srcset="my-image-900w.jpg,
             my-image-1350w.jpg 1.5x,
             my-image-1800w.jpg 2x"
     src="my-image-900w.jpg" alt="how would you describe it?">

If I had a device with a 2x pixel density screen, it would load only my-image-1800w.jpg and ignore the others.

For deciding what widths to choose I would match the css media-queries. Then so long as you have an option for small screens (say 300w) you should be all set. Personally I use boostrap as a framework, so I use the same widths to load my responsive images, plus a portfolio size for screens larger than 2000 pixels.

Hope this helps!

Upvotes: 2

Related Questions