解释 HTML5 中 figure 标签的用法
html5web developmentfront end technology更新于 2025/2/17 23:08:17
HTML5 中的 <figure> 元素表示独立内容(例如图片、图表、代码清单、插图等),并附带一个可选的标题,该标题使用 <figcaption> 元素指定。图片、其标题和内容被视为一个整体。
通常,<figure> 元素在文档的主流程中被引用。即使我们将其移除或移动到文档的其他部分,图片也不会影响文档的流程。主流程保持不变。
<figure> 标签的用法
在 HTML5 之前,无法通过 HTML 以语义方式为图片添加标题。如果我们想添加标题或描述,就必须添加一个带有类名或类似内容的段落。现在,HTML5 中新增了 <figure> 标签。
HTML5 中的 <figure> 标签主要用于处理图像、视频、音频等媒体内容。它还可以与 <figcaption> 标签配合使用,为我们的内容提供标题或描述。它提供了一种在文档中组织内容的语义方式。
语法
以下是 HTML5 中 <figure> 和 <figcaption> 元素的语法 -
<figure> <img src="path or link of an image"> <figcaption>caption or description</figcaption> </figure>
在上述语法中,
<img> 标签用于在文档中嵌入图像。
<figcaption> 用于指定特定图像的标题。
示例
在下面的示例中,我们使用 <figure> 元素在文档中插入图像。此外,我们还使用 <figcaption> 元素为图像定义标题 -
<!DOCTYPE html>
<html>
<head>
<title>Use of figure tag in HTML5</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<figure>
<img src="https://www.cainiaomax.com/assets/questions/media/14304-1693310967.jpg" height="500px" width="500px" alt="This is Basilica of Bom Jesus">
<figcaption>Fig.1 - Basilica of Bom Jesus, Goa</figcaption>
</figure>
</body>
</html>
执行上述程序后,我们可以在 <figure> 容器中看到一张图片及其标题。
示例
在下面的示例中,我们使用 CSS 来设置 <figure> 和 <figcaption> 元素的样式 -
<!DOCTYPE html>
<html>
<head>
<title>Use of figure tag in HTML5</title>
<style>
figure {
border: 1px black solid;
padding: 1em;
margin: auto;
}
figcaption {
background-color: seagreen;
color: white;
font-style: italic;
padding: 5px;
text-align: center;
}
</style>
</head>
<body>
<figure>
<img src="https://www.cainiaomax.com/assets/questions/media/14304-1693310967.jpg" width="100%" alt="This is Basilica of Bom Jesus">
<figcaption>Fig.1 - Basilica of Bom Jesus, Goa</figcaption>
</figure>
</body>
</html>

