4
votes

I am using responsive images by srcset and sizes attributes in <img>. I have 3 images with 3 different sizes (200x200, 400x400, 600x600). I need to switch them for different sizes of viewport as follows:

viewport size 1190px -> image size 555px
viewport size 991px -> image size 300px
viewport size 575px -> image size 130px
Any other viewport size -> image size 255px

to do this I coded as follows:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>responsive test</title>
</head>
<body>
    <img    src="Go-400_x_400.jpg"
            srcset="Go-200_x_200.jpg 200w,
                    Go-400_x_400.jpg 400w,
                    Go-600_x_600.jpg 600w"
            sizes=" (max-width:575px) 131px,
                    (max-width:991px) 300px,
                    (max-width:1199px) 555px,
                    255px"
            alt="responsivetest" >
</body>
</html>

As the definition, for different sizes, media query should select the appropriate image from srcset for each size. I expect 200x200 image for max-width:575px size, 400x400 image for max-width:991px size and 600x600 image for max-width:1191px size. But for all sizes only the 600x600 image will be loaded and no shifting images. How I solve this?

2

2 Answers

5
votes

Are you aware of the html5 picture tag?

It helps load alternate images base on media queries and screen sizes.

<picture>
  <source media="(min-width: 650px)" srcset="https://www.w3schools.com/tags/img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="https://www.w3schools.com/tags/img_white_flower.jpg">
  <img src="https://www.w3schools.com/tags/img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

Resize the browser to see different versions of the picture loading at different viewport sizes. The browser looks for the first source element where the media query matches the user's current viewport width, and fetches the image specified in the srcset attribute.

The img element is required as the last child tag of the picture declaration block. The img element is used to provide backward compatibility for browsers that do not support the picture element, or if none of the source tags matched.

Note: The picture element is not supported in IE12 and earlier or Safari 9.0 and earlier.

0
votes

Actually, the images are shifting but not showing because the browser cache records the large image. It is responsive for the devices correctly. I can see it by disabling the browser cache.