Skip to content

Latest commit

 

History

History
80 lines (50 loc) · 2.5 KB

23.picture-srcset-and-sizes-for-responsive-images.md

File metadata and controls

80 lines (50 loc) · 2.5 KB

24. Picture, srcset and sizes for responsive images

What is a responsive image?

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.

Methods to enable responsive images are

  • srcset attribute.
  • sizes attribute.
  • picture element.

Srcset Attribute

  • Used when we want to show the same image in different sizes based on the device pixel ratio.

Options in srcset

  • 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

Pros & Cons are

Pros

  • Srcset attribute only solves the problem for device pixel ratios.

Cons

  • 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.

Sizes Attribute

  • 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.

Picture Element

  • 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.