使用图片元素作为容器而不是 div

Use of picture element as a container instead of a div

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

根据 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.

因此,可以安全地假设以下 HTML 在语义上更正确吗?

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

不,第二个版本在语义上并不更正确,因为图片元素旨在用于在不同情况下可能使用多个源文件的情况。

HTML 社会化:

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.

最好单独使用图片标签。您可以将其包装在 div 中以用于样式或间距目的,但是,除非您计划以编程方式显示内容,否则请尽可能单独使用它。

图像元素的语义正确容器是图形元素 - 文档 - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure

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

此元素有一个可选的 figcaption 元素,可以是第一个 child 或最后一个 child - 以提供标题(与图像相关的上下文文本)。

作为第一个child(图片上方

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

作为最后一个 child - 图片下方

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

请注意,您可以将图形和包含的 figcaption 和 img 元素设置为您想要的任何样式。

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>