2

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.

Matt
  • 88
  • 1
  • 11

2 Answers2

4

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.

Nicolas Hoizey
  • 1,954
  • 1
  • 17
  • 24
  • 1
    second link is broken, might as well link to the offical w3c draft issue at https://github.com/w3c/csswg-drafts/issues/5796 – schellmax Jul 05 '21 at 07:38
0

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.