To add text under an image in HTML, the recommended and semantic method is to use the <figure>
and <figcaption>
elements.
The most effective way to place text directly beneath an image as a caption is by pairing the image within a <figure>
element and using the <figcaption>
element for the text. As referenced, the <figcaption>
element sets an image caption for a <figure>
element. To achieve a caption below the picture, place the <figcaption>
element after the <img>
tag within the <figure>
.
Using <figure>
and <figcaption>
This approach groups the image and its caption together semantically, indicating that they are related content. This is beneficial for accessibility and search engines.
Steps:
- Wrap your
<img>
tag within a<figure>
element. - Place your desired text within a
<figcaption>
tag. - Ensure the
<figcaption>
tag comes after the<img>
tag inside the<figure>
element.
Example HTML Code:
<figure>
<img src="your-image-url.jpg" alt="Description of the image">
<figcaption>Your caption text goes here, appearing right below the image.</figcaption>
</figure>
- The
<figure>
element is a container for self-contained content like images, diagrams, code snippets, etc. - The
<figcaption>
element provides a caption or legend for the content of its parent<figure>
.
Benefits of Using <figure>
and <figcaption>
- Semantic Correctness: Clearly indicates that the text is a caption for the image.
- Accessibility: Screen readers and other assistive technologies can better understand the relationship between the image and its caption.
- Structure: Provides a clear, organized structure for image content.
Alternative Method (Less Semantic)
While not the semantic standard like <figure>
and <figcaption>
, you could simply place a paragraph <p>
tag containing your text immediately after the <img>
tag. However, this method lacks the semantic grouping of <figure>
and doesn't explicitly define the text as a caption related to the image in the same way <figcaption>
does.
<img src="your-image-url.jpg" alt="Description of the image">
<p>This text will appear below the image, but isn't semantically linked as a caption.</p>
For best practice, especially for captions, the <figure>
and <figcaption>
method is strongly recommended as it explicitly marks the text as an image caption, enhancing structure and accessibility.