Captions
Fancybox supports captions out of the box. Use CSS to center content or completely change the position.
Basic usage
Use data-caption
attribute to specify the content of the caption. If you want to use HTML content, you need to escape it:
<a
href="image-a.jpeg"
data-fancybox="gallery"
data-caption="Optional caption,<br />that contains <em>HTML</em> code"
>
<img src="thumbnail-a.jpeg" />
</a>
When using Fancybox programmatically, use the caption as the key for the slide object:
new Fancybox([
{
src: "<p>Lorem ipsum dolor sit amet.</p>",
caption: "Caption #1",
type: "html",
},
]);
Customize content
Use a caption
option that accepts a function and is called for each element in the gallery.
An example of how to insert the current slide index and the total number of slides in the gallery in the caption:
Fancybox.bind("[data-fancybox]", {
caption: (fancybox, slide) => {
const caption = slide.caption || "";
return `${slide.index + 1} / ${
fancybox.carousel?.slides.length
} <br /> ${caption}`;
},
});
Different source
If it's more convenient, you can, for example, store the content of the caption in another HTML element. Example:
<figure data-fancybox="gallery" data-src="https://lipsum.app/id/1/1600x1200">
<img src="https://lipsum.app/id/1/200x150" />
<figcaption>Caption #1</figcaption>
</figure>
Fancybox.bind("[data-fancybox]", {
caption: function (fancybox, slide) {
const figurecaption = slide.triggerEl?.querySelector("figurecaption");
return figurecaption ? figurecaption.innerHTML : slide.caption || "";
},
});
If you want to use the alt
attribute of the thumbnails as caption content, that's easy:
Fancybox.bind("[data-fancybox]", {
caption: function (fancybox, slide) {
return slide.thumbEl?.alt || "";
},
});
Change position
Since Fancybox elements are positioned only with the help of CSS, you can easily change the position of the caption. With just one line of CSS, you can, for example, place it above the content or next to it. Example:
.fancybox__slide.has-caption {
flex-direction: row;
}
.fancybox__caption {
max-width: 250px;
padding: 1rem 3rem 1rem 1rem;
}