One, foreword

In Web development, it is often necessary to scale the picture elements according to the different aspect ratio/size of the user’s mobile phone screen to improve the user experience. However, some pictures must be guaranteed to be complete and cannot be stretched or cropped, which requires the development of different picture materials for different screen sizes.

At one time, this would have been done using JS, but today, the element brings native ability to solve all kinds of problems……

Here is :

Second, the introduction

The element is a block element that can have zero or morechildren and one
child. If there is no
element, the picture will not be displayed.

is an inline element, which itself contains no style and should not be set. Has srcset and media properties. Rcset is used to specify image resources. The media attribute is used to set the media query. Images that match the media query source will be replaced with SRC and displayed.

Therefore, the media attribute can help us skip JS and directly complete the responsive loading of images.

Third, in actual combat

Set different source for different aspect ratio:

The width and height of the image should be set to

<picture>
    <source media="(min-aspect-ratio: 375/667)" srcSet="https://gw.alicdn.com/imgextra/i3/O1CN01hPKi8523CLuEqCID9_!! 6000000007219-2-tps-340-246.png">
    <img class='image' src="https://gw.alicdn.com/imgextra/i2/O1CN01vXeME91qv9cfeheHo_!! 6000000005557-2-tps-340-300.png">
</picture>
Copy the code

compatibility

All supported except IE

Incompatible browsers will simply adopt child elements<img>Set the picture.