HTML Course 6.3 Figures and captions (figure, figcaption)
6.3 Figures and Captions (<figure>, <figcaption>)
The HTML5 <figure> element represents self-contained content, such as illustrations, diagrams, photos, code listings, etc.,
optionally with a caption provided by <figcaption>. A <figure> can be moved out of the main flow of the document without
affecting the document’s meaning.
1. Semantics and Accessibility
<figure> groups related media and its caption. Screen readers announce the group as a unit.
<figcaption> must be the first or last child of <figure>. It provides the legend or description.
If you need ARIA enhancements, you can use aria-labelledby or aria-describedby on <figure>.
2. Basic Usage
A simple example: an image with a caption.
Sunset over the mountains.
3. Caption Placement
You can place <figcaption> either before or after the media content:
Diagram of the water cycle.Diagram of the water cycle.
4. Responsive Images in <figure>
Use <picture> or srcset inside <figure> for responsive images:
Quarterly sales trends for 2023.
5. Figures with Inline SVG, Code, or Multimedia
<figure> works not only for images but for any self-contained content:
a) Inline SVG
Red circle drawn with inline SVG.
b) Code Snippet
// JavaScript function to add two numbers
function add(a, b) {
return a + b;
}
Example of a simple add function in JavaScript.
c) Video with Caption
Promotional video showcasing our new product line.
6. Nesting and Grouping
You can nest multiple media inside one <figure>, but only one <figcaption>:
Installation steps: 1, 2, and 3.
7. Best Practices and Tips
Always provide a meaningful alt attribute for images.
Keep captions concise but descriptive.
Use <figure> for standalone illustrations or media—avoid using it for purely decorative elements.
Only one <figcaption> per <figure> and it must be its immediate child.
For enhanced accessibility, use aria-describedby or aria-labelledby if the caption needs to be referenced externally.
Avoid putting unrelated block elements inside <figure>; keep content self-contained.
Leave a Reply
You must be logged in to post a comment.