When you put an image in a document, it often needs a caption — a line of text underneath that explains what the image shows. The <figure> and <figcaption> elements are designed exactly for this. They group an image with its caption in a semantically meaningful way.
Figure and Figcaption Basics
Wrap an image (or any content) in a <figure> tag, then add a <figcaption> inside it. The figcaption becomes the visible caption for the figure. Search engines and screen readers understand this relationship, which is great for accessibility.
<figure>
<img src="sunset.jpg" alt="A beautiful sunset over the ocean">
<figcaption>Sunset over the Indian Ocean, taken from Watamu Beach</figcaption>
</figure>
Figure Is Not Just for Images
While figures are most commonly used with images, you can use them for any self-contained content that is referenced from the main text — code blocks, charts, poems, quotes, or even audio and video. The key is that the figure content is referenced but not essential to the flow of the document.
<figure>
<pre><code>
function greet(name) {
return `Hello, ${name}!`;
}
</code></pre>
<figcaption>A simple JavaScript greeting function</figcaption>
</figure>
Positioning the Caption
The <figcaption> can go either before or after the image inside the figure element. Most people put it after the image so the caption appears below, but putting it before works too if you want the caption on top.
<figure>
<figcaption>Above the image</figcaption>
<img src="chart.png" alt="Monthly sales chart">
</figure>
Styling Figures with CSS
Figures are block-level elements with a default margin. You can style them to center the image, add borders, or create magazine-style layouts. The <figure> element gives you a natural container for this kind of styling.
<style>
figure {
margin: 24px auto;
text-align: center;
max-width: 500px;
}
figure img {
width: 100%;
border-radius: 8px;
}
figcaption {
margin-top: 8px;
font-style: italic;
color: #666;
}
</style>