Fetch an image based on Screen-Resolution [via HTML Only]

Viewed 147

In a recent interview I was asked by the interviewer that you got 2 images:

  1. One large resolution image that you have to show on laptops & desktops.
  2. One small image that you have to show only on mobiles.

You have to fetch a certain image (1 out of these 2) based on "screen resolution" only by the help of HTML Only. You should not do this with help of CSS/JS/jQuery!

Though, my HTML is pretty good, but I could not answer this. Anybody, has any knowledge of what the interviewer meant? or what is the correct Solution?

2 Answers

You can do this thing by using picture tag. check this example below.

<picture>
  <source media="(min-width:465px)" srcset="https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg">
  <source media="(min-width:600px)" srcset="https://webneel.com/wallpaper/sites/default/files/images/08-2018/3-nature-wallpaper-mountain.jpg">
  <img src="https://cdn141.picsart.com/297499064115201.jpg?type=webp&to=crop&r=256" alt="Flowers" style="width:auto;">
</picture>

check this fiddle for better results, just resize the result window.

check it here for more detail.

<img srcset="img-480w.jpg 480w,img-800w.jpg 800w" sizes="(max-width:600px)480px,800px" src="img-800w.jpg" alt="image">

You indicate with srcset that img-480w intrinsic width is 480px wide, img-800w is 800px wide.

With sizes you indicate that for a screen with a max width of 600px to use the 480px image and bigger than that to use the 800px image

Related