A responsive image is an image which fits any form factor, given the image is shown. It can a laptop, a desktop, a tablet or mobile devices.
- srcset attribute.
- sizes attribute.
- picture element.
- Used when we want to show the same image in different sizes based on the device pixel ratio.
- x descriptor - device pixel ratio
- w descriptor - width of the image
Example:
<img src="logo.png" srcset="logo.png 1x", srcset="logo.png 2x", srcset="logo.png 300w">
- 1x for device pixel ratio of 1
- 2x for device pixel ratio of 2
- 3w is the width of the image, which is 300px
- src attribute is used as a fallback for the browsers which doesn't support srcset
- Srcset attribute only solves the problem for device pixel ratios.
- We will get the same image for smaller devices and larger devices which has the same pixel ratio.
This is where sizes attribute comes in.
- Used when we want a different size image (width, height) on a different screen sizes.
- Sizes attribute is used along with the w descriptor of srcset attribute.
Example:
Let's add sizes attribute to show an image in half of the viewport width.
Example:
<img src="logo.png" sizes="50vw" srcset="logo.png 200w", srcset="logo.png 400w", srcset="logo.png 600w">
- Now the browser will decide which image to download based the browser width and the device pixel ratio.
- Used when we want to show different image depending on the rendered size of the image.
- Picture element is the container for other elements that controls the image.
Example:
<picture>
<source media="(max-width: 1024px)" srcset="logo.png 1x, logo.png 2x, logo.png 3x">
<source media="(max-width: 768px)" srcset="logo.png 1x, logo.png 2x, logo.png 3x">
<img src="logo.png" />
</picture>
- Source element is chosen based on the media attribute's media query which holds true.
- Picture element should contain a img tag in order to show corresponding image.
More information on picture, srcset, sizes.