Skip to content

Image Caption

Image Caption components are used to group an image with a caption. This component is useful for displaying images with a caption that provides context to the image.

Ipsum dolor sit esse fugiat sint enim minim.
<ImageCaption
image={{
src: 'https://place-hold.it/400x300',
alt: '',
width: 400,
height: 300
}}
caption={{
text: 'Ipsum dolor sit esse fugiat sint enim minim.'
}}
/>

API Reference

This component is based on the <figure> element and can take in any additional HTML attributes. The following are the custom props that can be passed to the component.

Prop Type Default
image
HTMLAttributes<'img'>
src *
string
alt *
string
width
number
height
number
decoding
'async' | 'sync' | 'auto'
loading
'lazy' | 'eager'
caption
HTMLAttributes<'figcaption'>
text
string

Accessibility

The <ImageCaption> component has some accessibility considerations baked into it. The following are some of the key accessibility features that are included in the component and worth considering:

  • When the image is decorative, the alt property can be omitted and will automatically be converted to alt="".
  • If an image has a caption, the alt will default to that caption text unless otherwise specified.
  • If an image has the same caption and alt text, the caption will be given the aria-hidden="true" attribute to prevent duplication of content to screen readers.

Astro Component

Depending on the framework, it’s sometimes beneficial to use a component. In this case, we have put together the following Astro component to serve as a blueprint for how you could possibly set up an Image Caption component, and what properties to consider.

ImageCaption.astro
---
import { Image } from 'astro:assets'
import type { ImageMetadata } from 'astro'
import type { HTMLAttributes } from 'astro/types'
interface ImageProps extends ImageMetadata {}
interface CaptionProps extends HTMLAttributes<'figcaption'> {}
interface Props extends HTMLAttributes<'figure'> {
image: {
alt: string
} & ImageProps
caption: {
text: string
} & CaptionProps
}
const {
image: { alt, ...image },
caption: { text, ...captionAttrs },
...attrs
} = Astro.props
---
<figure {...attrs}>
{image && <Image alt={alt || ''} {...image} />}
{
text && (
<figcaption {...captionAttrs} aria-hidden={alt === text}>
{text}
</figcaption>
)
}
</figure>