How to Use the figure Element — Grouping a Diagram or Code Example
figure groups content that readers can understand as one piece, such as a diagram, photo, or code example. You can add an explanation with figcaption.
The short answer
Use figure for content that can be referred to as one piece from the main text. It is not only for pictures; it can also group a chart, code listing, or poem.
figcaption explains that piece. If you use it, place it first or last inside figure.
Group a code example
This example groups code with its explanation. aria-labelledby connects the figure to the text used as its accessible name.
const total = prices.reduce((sum, price) => sum + price, 0);
An image explanation and a figure explanation
When you include an image, alt is a short text alternative for the image. figcaption explains the group that contains the image. They have different jobs, so they do not always need to repeat the same words.
For example, alt can say what is in a photo. figcaption can give its location or explain how the photo relates to the text.
A short alt may not explain all the important numbers or connections in a chart or diagram. Use alt to briefly say what the image shows, then add the details in nearby text or a table. See the chart and diagram example.
A simple guide
- Use it when a diagram or code example can be referred to as one piece from the text around it.
- Use
figcaptionwhen the whole piece needs a visible explanation. - A small image used as part of a sentence may not need a
figurearound it. - A side note or an advertisement may belong in a different element if it is separate from the main text.
Putting content in figure does not make it unrelated to the main text. The figure is still part of the surrounding flow of content.
Common mistakes
- Putting every photo in a
figure. A small image that is part of a sentence may not need its own group. - Using
figcaptioninstead of an image'salt. Think about the short text needed when the image itself is unavailable. - Putting
figcaptionin the middle or using several captions. The standard allows one caption, at the start or end.
A little more detail
Numbering a figure and referring to it by that number can keep the reference clear if the figure moves. A phrase such as “the chart above” can become confusing after the page is rearranged.
Browsers and versions of HTML-AAM can differ in how they expose a figure's name to assistive technology. When a figure needs a name, connect it to its caption with aria-labelledby and check the target browsers.
Related pages
For the image itself, see the img element. For a table title, see the caption element. For standards and browser Accessibility Tree observations, see the figure topic in Yugien Atlas.