17. Images and Captions (Images, <figure> & <figcaption>)
<img>, alt, loading='lazy', <figure>, <figcaption>
Real-life analogy
The caption (photo description) written below a picture in a book works like figure and figcaption.
Explanation
Modern HTML tags for displaying images:
<img>: The main image tag (self-closing).src(address) andalt(alternative text) are mandatory. Addingloading="lazy"makes the photo load only when the user scrolls to it.<figure>and<figcaption>: A semantic container for adding an image and its official caption right below it.
Golden rules
- Always provide the
altattribute. If the photo is purely decorative, leave an emptyalt="". - Fix the image's
widthandheightin advance to prevent the page from jumping.
Common mistake
Putting a huge 5MB photo directly on the website. Always compress photos before using them.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<figure style="margin: 0; max-width: 250px; border: 1px solid #cbd5e1; padding: 10px; border-radius: 8px; background: #f8fafc;">
<img src="https://images.unsplash.com/photo-1546527868-ccb7ee7dfa6a?w=300"
alt="White and brown puppy"
loading="lazy"
style="width: 100%; border-radius: 6px;">
<figcaption style="font-size: 11px; color: #64748b; text-align: center; margin-top: 6px;">
Figure 1.1: A cute little puppy (<figcaption>)
</figcaption>
</figure>
</body>
</html>
Quick quiz
Which semantic tag is used to add an official caption (description) below an image?
- <caption>
- <p>
- <figcaption>
- <title>
Show answer
Answer: <figcaption>
<figcaption> is used inside <figure> to write the description of the photo.