Posted on December 23, 2023 | #markdown

thumbnail

Add captions to images in Obsidian

You can get true figures with captions by using the <figure> and <figcaption> HTML elements. Since any HTML is also valid markdown, this works perfectly fine.

But we are writing markdown precisely because writing in HTML sucks a little. So here is a more ergonomic solution for the Obsidian markdown editor.

Head to Settings > Appearance. At the bottom, there is a CSS Snippets section. You can customize the editor by putting CSS snippets there, activate them and Obsidian will load and apply them automagically.

The snippet that works pretty well is this little guy:

.image-embed[alt]:after {
    content: attr(alt);
    display: block;
    margin: 0.2rem 1rem 1rem 1rem;
    font-size: 90%;
    line-height: 1.4;
    color: var(--text-faint);
}

Credit: I politely stole this snippet from this forum post.

This snippet takes the alt property of the image itself and displays it as the caption. I like my captions centered too, so I just add a text-align: center to the thing.

Different approach

This does not work for obsidian due to how it wraps everything in weird divs. But it’s interesting nevertheless.

CSS has a less known + specifier, that defines if a an element’s previous sibling is of some type. So you can for example follow up an image by a <em> text and render that as a caption!

In Markdown it would look something like this:

![alt text](/your/image.png) *This is your caption now!*

Putting the caption behind the image like this will cause them to be placed inside the same <p> element! If you have more control over the markdown parsing process, you might even get away by putting it directly on the next line, which is more readable:

![alt text](/your/image.png)
*A caption right on the next line.*

You can then detect this scenario with the following CSS snippet:

p:has(img) {
	display: flex;
	flex-direction: column;
}

p img + em {
	/* Style your caption however you want */
}

The p:has(img) statement is a little broad, but in parsed markdown, paragraphs are very unlikely to have more than 1 image. I mean.. it’s possible.. but nobody writes markdown like that (I hope).