DEV Community

Cover image for HTML tags | picture
Carlos Espada
Carlos Espada

Posted on • Edited on

HTML tags | picture

It is used to offer different versions of an image for different screens or devices. To do this, zero or more <source> elements and one <img> element must be specified inside.

The browser will look at the srcset, media and type attributes of each <source> and of the one it considers most appropriate it will load the image specified in its srcset attribute.

If the browser does not find any valid option or does not support the <picture> element, then it loads the <img> that we have indicated as the default image. This <img> is also used to set the size of the displayed image, its presentation and some of its attributes, such as alt.

Some use cases for <picture> are:

  • Art Direction: cropping or modifying images for different media conditions (for example, loading on smaller screens a simpler version of an image that has a lot of detail).
  • Offer alternative image formats: for cases in which certain formats, such as AVIF or WEBP, are not supported, but it is interesting to specify them due to the advantages they offer if they can be used.
  • Save bandwidth and speed up page load time: by loading the most suitable image for user viewing.

If you are going to use versions with higher pixel density for high resolution displays (retina), use src in the <img> element. This allows browsers to opt for the less dense versions in data saver modes, and it is not necessary to write media conditions explicitly.

You can use the CSS object-position property to adjust the position of the image within the element's frame, and the object-fit property to control how the image is resized to fit within the frame. These two properties must be used in the <img> element, not in the <picture>.

  • Type: -
  • Self-closing: No
  • Semantic value: No

Definition and example | Support

Top comments (0)