Mixing srcset and picture for responsive images

1.3k views Asked by At

At my work we have our own framework and we're trying to think of the best way to implement responsive images. Images are generated from the backend code and we would like to have a single control that solves all use cases.

Since srcset seems to be the best solution for responsive images and Picture seems to solve two other cases (Art direction and modern image formats like WebP and Jpeg XR) we want to see if we can combine them.

Since the picture element is mostly used with a element with a media query inside it is an instruction to browser to use this if it meets certain conditions.

Srcset however let's the browser choose the picture bases on some calculations.

Would it somehow be possible to keep the choice to the browser within the picture element?

Something like this for example.

<picture>
    <source sizes="(min-width: 800px) 50vw, 100vw" srcset="small.webp 100w, medium.webp 200w, large.webp 300w">
    <source sizes="(min-width: 800px) 50vw, 100vw srcset="small.JPG 100w, medium.JPG 200w, large.JPG 300w">

    <img src="small.jpg" alt="Some image" />
</picture>

Would appreciate any help :)

1

There are 1 answers

0
Saurabh Kirtani On

You are correct. The first snippet is right:

   <source sizes="(min-width: 800px) 50vw, 100vw" srcset="small.webp 100w, medium.webp 200w, large.webp 300w">

The second one is not:

<source sizes="(min-width: 800px) 50vw, 100vw srcset="small.JPG 100w, medium.JPG 200w, large.JPG 300w">

You can also use the type attribute within the source element to find out support of that image type on the browser. Something like this:

<picture>

<source media = "(max-width: 30em)" type="image/vnd.ms-photo" srcset="images/small/space-needle.jxr 1x, images/small/space-needle-2x.jxr 2x, images/small/space-needle-hd.jxr 3x >
<source media = "(max-width: 30em)" type="image/jpg" srcset="images/small/space-needle.jpg 1x, images/small/space-needle-2x.jpg 2x, images/small/space-needle-hd.jpg 3x >
<img src="space-needle.jpg" alt="Space Needle">

</picture>

More details available here.