DEV Community

Cover image for Using the HTML `picture` element to show a WebP image
Joe Attardi
Joe Attardi

Posted on

Using the HTML `picture` element to show a WebP image

The WebP image format has been around since 2010 when the standard was first announced. One benefit of using WebP images is that they are smaller than both JPEGs and PNGs, sometimes significantly.

WebP is supported in almost all modern browsers, as can be seen here. However, it currently is not supported in Safari and IE11. So we can't use a standard <img> element, as the image will not display in these browsers.

Luckily there is a solution with the HTML <picture> element. This is a very powerful and flexible element that lets you define multiple sources for an image.

First, convert your image to WebP. There are several easy online converters that can do this. Next, use a <picture> element:

  <source type="image/webp" srcSet="/my-image.webp" />
  <img src="/my-image.jpg" />
Enter fullscreen mode Exit fullscreen mode

The last child of a <picture> element is a fallback <img> element. This will be used if the browser does not support WebP. This also allows the image to be shown on browsers that do not support the <picture> element.

Speaking of browser support, it's pretty decent. All modern browsers (Edge, Firefox, Chrome, and Safari) support <picture>. It's not supported in IE11, but the fallback <img> element will be used instead.

Top comments (1)