background

Yesterday, I suddenly remembered the img-srcset attribute I tried two years ago. When I was rushing to finish the course design, I found it worked in Firebox, but it was not used at all in Chrome. However, its compatibility is as follows:

Imgset compatibility

In fact, I think compatibility is quite good, so I still want to try again!

introduce

Srcsert comes in two versions:

  1. The old version

    ! [](mm@1x.jpg)Copy the code
  2. A new version of

    <img src="./img/x-pc.png"
         srcset="./img/x-pc.png 300w, ./img/[email protected] 500w"
         sizes="(min-width: 300px) 400px, calc(100vw - 2rem)">Copy the code

emm….. The new version, in fact, is very simple:

  1. srcsetThis property defines the image and tells the browser how wide your image is
  2. sizesThis attribute defines the image width in different cases. In addition to not using % (confusing, but vw instead), calc() can also be used

Take a look at

  • Width 250px
250px

  • Width 300px
300px

If you are too lazy to record a GIF, the browser will load double sizes and replace sizes which specifies the size of the image. For example, in the first example the size of the image is constant 500px.

  1. Give priority to high-quality images
  2. Loading cached images is preferred if there is a cache

The advanced

Let’s explore the w unit, starting with sizes. Sizes is equivalent to dynamically defining the width and height of the image, and then we make some changes to the above example:

<img src="./img/x-pc.png"
        srcset="./img/x-pc.png 150w, ./img/[email protected] 250w"
        sizes="(min-width: 200px) 400px, calc(100vw - 20px)">Copy the code

150px

171px

W just tells the browser what size I think the image is, and the browser calculates a ratio based on the values you give it, for example the ratio above is 2, and multiplies sizes below: Actual render size = (original size/declared size) * corresponding sizes

Why do you do that?

I guess that if you press W equal to the width of the picture, it is not suitable for high-quality pictures, so W just serves as a description of the size of the picture, just like your parents, I think XXXXXX.

conclusion

I’ll just write and you can leave a message if you think something’s wrong