Home > Software engineering >  Picture source with srcset
Picture source with srcset

Time:02-10

I want to use tag and 3 image formats. avif \ webp \ png. At the same time, but not to forget about retina displays.

At the moment I came up with something like this format:

<picture>
    <source srcset="components/header/img/logo.avif, components/header/img/[email protected] 2x" type="image/avif">
    <source srcset="components/header/img/logo.webp, components/header/img/[email protected] 2x" type="image/webp">
    <img  src="components/header/img/logo.png" srcset="components/header/img/[email protected] 2x" alt="Logo">
</picture>

But how much of this is correct ? Maybe it should be implemented in some other way ?

CodePudding user response:

While the standard HTML <img> element doesn't support compatibility fallbacks for images, the <picture> element does. <picture> is used as a wrapper for a number of <source> elements, each specifying a version of the image in a different format or under different media conditions, as well as an <img> element which defines where to display the image and the fallback to the default or "most compatible" version.

<picture>
   <source srcset="diagram.svg" type="image/svg xml">
   <source srcset="diagram.png" type="image/png">
   <img src="diagram.gif" width="620" height="540"
   alt="Diagram showing the data channels">
</picture>

More info developer.mozilla.org

I hope I was helpful

CodePudding user response:

You can combine both concepts via an art-direction rule.

The art direction concept is basically intended to switch between different image versions with different aspect ratios depending on your viewport size.

Example from german web studio "kulturbanause":

<picture>
  <source media="(min-width: 56.25em)" srcset="large.webp" type="image/webp">
  <source media="(min-width: 56.25em)" srcset="large.jpg">

  <source media="(min-width: 37.5em)" srcset="medium.webp" type="image/webp">
  <source media="(min-width: 37.5em)" srcset="medium.jpg">

  <source srcset="small.webp" type="image/webp">
  <source srcset="small.jpg">
  <img src="fallback.jpg" alt="">
</picture>

Use svg if feasible (logos, info graphics etc)

Referring to your code example referencing a logo img:
Most likely, your logo could be used as a svg.
If it's created (or optimized) well, you don't need any HiRes candidates. (and most likely svg will also wipe the floor with raster images regarding filesize)

See also: MDN Docs: Responsive images

  •  Tags:  
  • Related