Use of picture element as a container instead of a div

870 views Asked by At
<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>
2

There are 2 answers

0
gavgrif On BEST ANSWER

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>

4
AudioBubble On

No, the second version is not more semantically correct because the picture element is intended to be used when there are multiple sources files that might be used under different circumstances.

HTML Specification:

The picture element is a container which provides multiple sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors. It represents its children.

It would be best if you use the image tag on its own. You can wrap it in a div for styling or spacing purposes, but, unless you plan on displaying content programmatically, use it alone if it is possible.