#How can I add captions to an image?
1 messages · Page 1 of 1 (latest)
Hi @oak flax. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can add captions to images in both .md and .mdx files.
For .md files, Astro uses standard Markdown !**alt** (src) syntax. However, this syntax does not support adding captions directly.
For .mdx files, you can use Astro’s <Image /> component and JSX <img /> tags by importing both the component and your image. However, these also do not support captions directly.
If you need more control over your image attributes, including adding captions, you can create a custom Markdoc image tag. This involves creating a custom Astro component that receives the necessary props and renders an image with a caption. Here's an example:
// src/components/MarkdocFigure.astro
import { Image } from "astro:assets";
interface Props {
src: ImageMetadata | string;
alt: string;
width: number;
height: number;
caption: string;
}
const { src, alt, width, height, caption } = Astro.props;
<figure>
<Image {src} {alt} {width} {height} />
{caption && <figcaption>{caption}</figcaption>}
</figure>
Then, you can configure your custom image tag to render your Astro component:
// markdoc.config.mjs
import { component, defineMarkdocConfig, nodes } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
tags: {
image: {
attributes: nodes.image.attributes,
render: component('./src/components/MarkdocFigure.astro'),
},
},
});
Finally, you can use the image tag in Markdoc files to display a figure with caption, providing all the necessary attributes for your component:
{% image src="./astro-logo.png" alt="Astro Logo" width="100" height="100" caption="a caption!" %}