Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add a caption to an image

Short answer

Wrap the image in <figure> and put the caption in <figcaption>:

<figure style="margin: 0; width: 240px;">
  <img src="/media/photo-400x250.jpg" alt="A pink flower in the garden" style="width: 100%; height: auto; display: block;">
  <figcaption style="margin-top: 6px; color: gray; font-size: 14px;">Photo: the city garden in May</figcaption>
</figure>

<figure> binds the image and the caption into one whole, and screen readers read them together. <figure> has default side margins — they are usually reset.

A caption over the image

The caption can sit on the bottom edge of the image with a translucent background:

<style>
  .photo { position: relative; width: 240px; margin: 0; }
  .photo img { width: 100%; height: auto; display: block; border-radius: 8px; }
  .photo figcaption { position: absolute; inset: auto 0 0; padding: 6px 10px; border-radius: 0 0 8px 8px; background: rgb(0 0 0 / 0.6); color: white; }
</style>
 
<figure class="photo">
  <img src="/media/photo-400x250.jpg" alt="A pink flower">
  <figcaption>City garden, May</figcaption>
</figure>

alt and the caption

alt describes what is shown for those who cannot see the image. The caption is a comment visible to everyone: the author, the place, an explanation. Do not repeat the same text in both.

Common mistake

The caption is written as a plain paragraph under the image. Visually there is no difference, but the link between them is lost: for the browser and search engines it is just nearby text. Use <figure> and <figcaption>.

Functions used in this recipe

  • <figure> — A self-contained illustration — an image, a diagram, code or a quote — with a `<figcaption>` caption.
  • <img> — An image.
  • alt — The text alternative for an image: read by screen readers and shown if the image fails to load.
  • position — How an element is positioned: in the normal flow or by offsets.

Thanks for reading!

Donate to the site — we work hard for you.