HTML - Responsive Img
Table of Contents
1 - About
A responsive image is when a different physical image (in width or resolution) is served for the same logical image depending on the characteristic of the device property (width, device pixel ratio)
2 - Articles Related
3 - Technical List
3.1 - HTML definition
3.1.1 - srcset
To define a set of responsive images, you can use the srcset and sizes attributes. See HTML - Responsive Image with the ''SrcSet'' and ''sizes'' attributes
<img src="image.png" data-srcset="image.png 1000w, image-2x.png 2000w">
3.1.2 - picture
To define a set of responsive images, you can also use the picture element
<picture>
<source media="(max-width: 799px)" srcset="480w.jpg">
<source media="(min-width: 800px)" srcset="800w.jpg">
<img src="800w.jpg" alt="Default if the media condition are not met">
</picture>
3.2 - Loading
3.2.1 - preloading
You can preload the responsive image
- One image
<link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)">
<link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)">
- A set
<link
rel="preload"
as="image"
href="wolf.jpg"
imagesrcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
imagesizes="50vw"
/>
3.2.2 - lazy loading
You can lazy load them also.
Example with lozad and the srcset
<img class="lozad" data-src="image.png" data-srcset="image.png 1000w, image-2x.png 2000w">
3.3 - Styling
To resize the image properly on width and height, you should apply the following CSS rules.
.responsive_img {
max-width: 100%;
height: auto;
}