0

I've this:

  <img class="poster" srcset="https://image.tmdb.org/t/p/original/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg 1024w,
                                        https://image.tmdb.org/t/p/w780/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg 700w,
                                        https://image.tmdb.org/t/p/w500/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg 400w"
                                sizes="100vw" 
            />

i want that the browser load the image in base the with of the screen, if it's mobile the w500, tablet w780 and pc original, how can i do it?

  • 1
    https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images – disinfor Mar 02 '19 at 17:08
  • 1
    Possible duplicate of [Img srcset auto resizing](https://stackoverflow.com/questions/33003846/img-srcset-auto-resizing) – YourPalNurav Mar 03 '19 at 09:01

1 Answers1

1

If you need to display the same image for all viewport-sizes, then I recommend you make the image behave like a flex-box to make it responsive. By doing so you don't have to worry about the @media (min-width) break-points. and the image will always fillup the whole viewport-width (100vw).

Here is such a code:

body {
  margin: 0;
  padding: 0;
}

.poster {
  max-width: 100%;
  display: block;
  height: auto;
}
<img class="poster" src="https://image.tmdb.org/t/p/original/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg" />

Using <img srcset="" sizes=""/> is recommended if you need to change the image for users on different displays.
If you want the userswith mobile to view Image-1,
Users with tablet to view Image-2 and
Users with desktops to view Image-3,
then you can do so easily by using <img srcset="" sizes=""/>.

Here is the code sample for achieving that,

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #222;
  margin: 0;
  padding: 0;
  height: 100vh;
}
<img src="https://picsum.photos/1024/512?image=0"
     srcset="https://picsum.photos/1024/512?image=2 1024w,
             https://picsum.photos/780/390?image=4 780w,
             https://picsum.photos/500/250?image=6 500w"
     sizes="(min-width: 1024px) 1024px, /* For Desktop users */
            (min-width: 780px) 780px, /* For Tablet users */
            500px">  /* Default for Mobile users */
Change the viewport width and you'll see the image change while increasing width.

I hope this helps.

Peace 🖖

YourPalNurav
  • 1,204
  • 9
  • 40