htmlpicture-element

Does setting `width` and `height` attributes in <picture> or its <img> do anything?


I want to start using WebP on my site. I'm converting code that looks like this:

<img src="example.jpg" width="100" height="100" alt="Example">

To code that looks like this:

<picture>
  <source srcset="example.webp" type="image/webp">
  <img src="example.jpg" width="100" height="100" alt="Example">
</picture>

Where is the correct place to put the width and the height attributes? Does simply using the height and width attributes in the <img> element work, even when a <source> image is selected?


Solution

  • Yes, using the height and width attributes in the <img> element (and nowhere else) does work as intended. You don't need to try to set any attributes on the <picture> element.

    Run this code snippet for proof:

    <p><code>&lt;img&gt;</code> without <code>height</code> and <code>width</code> attributes:</p>
    <picture>
      <source srcset="https://a.webpurr.com/Ql62.webp" type="image/webp">
      <img src="https://i.sstatic.net/mraCN.jpg" alt="Example">
    </picture>
    <p><code>&lt;img&gt;</code> with <code>height</code> and <code>width</code> attributes:</p>
    <picture>
      <source srcset="https://a.webpurr.com/Ql62.webp" type="image/webp">
      <img src="https://i.sstatic.net/mraCN.jpg" width="100" height="100" alt="Example">
    </picture>

    (If you see the images marked "JPEG", then you're using a browser that doesn't support WebP. If you don't see images, maybe the image host webpurr.com is down.)