02. img vs figure
Introduction
Section titled “Introduction”Both <img> and <figure> elements can display images, but they serve different purposes. The <img> element is for standalone images, while <figure> is for images with captions or that are referenced from the main content. Understanding when to use each improves semantic HTML and accessibility.
img Element
Section titled “img Element”For standalone images:
<img src="logo.png" alt="Company Logo">figure Element
Section titled “figure Element”For images with captions or referenced content:
<figure> <img src="diagram.jpg" alt="System architecture diagram"> <figcaption>Figure 1: System architecture</figcaption></figure>When to Use img
Section titled “When to Use img”Use <img> for:
- Decorative images
- Logos
- Icons
- Standalone images without captions
<img src="logo.png" alt="Company Logo">When to Use figure
Section titled “When to Use figure”Use <figure> for:
- Images with captions
- Diagrams and charts
- Images referenced in text
- Code examples with captions
<figure> <img src="chart.png" alt="Sales chart"> <figcaption>Figure 1: Quarterly sales data</figcaption></figure>Best Practices
Section titled “Best Practices”Use figure for Captioned Images
Section titled “Use figure for Captioned Images”<!-- Good: Image with caption --><figure> <img src="photo.jpg" alt="Landscape"> <figcaption>A beautiful mountain landscape</figcaption></figure>
<!-- Avoid: img without semantic caption --><img src="photo.jpg" alt="Landscape"><p>A beautiful mountain landscape</p>