'<source> media attribute - width of container rather than screen?

I'm using the <picture></picture> tag to responsively display an image after assessing the size of the container it's in.

Some example code:

<picture>
            <source media="(max-width: 70px)" srcset="IMAGE_URL">
            <source media="(min-width: 71px) and (max-width: 170px)" srcset="IMAGE_URL">
            <source media="(min-width: 171px) and (max-width: 270px)" srcset="IMAGE_URL">
            . . .
            <img src="IMAGE_URL" alt="An image">
</picture>

However, the <source media="(MEDIA_QUERY)" ... > part in an implementation of the format above considers the width of the entire screen, rather than the container that the <picture></picture> is currently inside.

Help on this is appriciated.



Solution 1:[1]

There is unfortunately no standard way (yet) to base responsive behavior upon a container instead of the browser viewport.

There are community efforts around Container Queries, but nothing has yet been defined, that could eventually become a standard.

There are several JavaScript libraries, like EQCSS, trying to provide solutions, but requiring JavaScript for a presentation —hence CSS— job is often not a good idea.

You can also look at CSS Conditions, but it also requires JavaScript.

Solution 2:[2]

You can use srcset and specify image size:

    <div class="container">
    <img src="image-200.jpg" 
        srcset="image-100.jpg 100w, image-200.jpg 200w,
                 image-400.jpg 400w, image-800.jpg 800w,
                 image-1000.jpg 1000w, image-1400.jpg 1400w,
                 image-1800.jpg 1800w" /> 
    </div>

Browser will download optimal image file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicolas Hoizey
Solution 2 White Crown