I continue to be impressed by the simplicity and power of Markdown.
Today, while exploring the API for Gatsbyβs Remark Images, I noticed the option: showCaptions
. 1
Add a caption to each image with the contents of the title attribute, when this is not empty. If the title attribute is empty but the alt attribute is not, it will be used instead. Set this option to true to enable this behavior. You can also pass an array instead to specify which value should be used for the caption β for example, passing
[βaltβ, βtitleβ]
would use the alt attribute first, and then the title. When this is set totrue
it is the same as passing[βtitleβ, βaltβ]
. If you just want to use the title (and omit captions for images that have alt attributes but no title), pass[βtitleβ]
.
It was the inclusion of βTitleβ that caught me off guard. Iβd never seen / used that before.
Iβd always imported my images as: 
.
It turns out, however, that thereβs a second argument that can be passed in after the path: the title.2

Example
I wanted to see what this would look like in a blog post - so, I tried adding the following image in a Gatsby blog: 
.
As expected, we see the alt
and title
properties present on the img
tag in the HTML:
<img class="gatsby-resp-image-image" src="/static/0006f3a2fe907f8d0b63c65e51983802/a111b/adam-solomon-hello.jpg" alt="hello!" title="adam solomon's hello">
Hereβs the relevant gatsby-config
β the images are a plugin as a part of the options for gatsby-plugin-mdx
β which is what Iβm using to compile the Markdown into HTML.
module.exports = {
plugins: [
βgatsby-plugin-sharpβ,
βgatsby-transformer-sharpβ,
{
resolve: βgatsby-plugin-mdxβ,
options: {
extensions: [β.mdxβ, β.mdβ],
defaultLayouts: {
default: require.resolve(β./src/components/layout.jsβ),
},
gatsbyRemarkPlugins: [
{
resolve: βgatsby-remark-imagesβ,
options: {
markdownCaptions: true,
linkImagesToOriginal: false,
showCaptions: [βtitleβ, βaltβ],
withWebp: true,
tracedSVG: { color: β#F00β, turnPolicy: βTURNPOLICY_MAJORITYβ },
},
},
],
},
},
],
};
Note: The showCaptions
option will only show either Title or Alt in the body of the document. Not both. Though, both are present in the HTML for screen readers.
For additional styling, I also found this blog post by xaprb informative.3
Top comments (2)