htmlpicturefill

Use of picture element as a container instead of a div


<div class="container">
  <img src="photo.jpg" alt="A Photo"/>
</div>

According to the picture element specification:

Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements.

The picture element is a container which provides multiple sources to its contained img element... It represents its children.

Therefore, is it safe to assume that the following HTML is more semantically correct?

<picture>
  <img src="photo.jpg" alt="A Photo"/>
</picture>

Solution

  • The semantically corect contaner for an image element is the figure element - documentation - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure

     <figure>
      <img src="photo.jpg" alt="A Photo"/>
    </figure>
    

    This element has an optional figcaption element that can be either the first child or the last child - to provide a caption (contextual text related to the image).

    as the first child (above the image

     <figure>
      <figcaption>A photo</figcaption>
      <img src="photo.jpg" alt="A Photo"/>
    </figure>
    

    As the last child - below the image

     <figure>
      <img src="photo.jpg" alt="A Photo"/>
      <figcaption>A photo</figcaption>
    </figure>
    

    Note that you can style the figure and contained figcaption and img elements to be whatever style you want.

    figure {
     text-align: center;
    }
    
    figcaption {
      margin-bottom: 8px;
      color: green;
    }
    figure img {
     border: solid 1px green;
     padding: 4px;
     border-radius: 4px;
    }
     <figure>
      <figcaption>A Fluffy kitten</figcaption>
      <img src="https://i.pinimg.com/originals/3e/6b/cd/3e6bcdc46881f5355163f9783c44a985.jpg" alt="A fluffy kitten" width="150"/>
    </figure>