Captions
Fancybox supports captions out of the box. Use CSS to customize the design or even change the position completely.
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:
html
<a
href="https://lipsum.app/id/31/1800x1200"
data-fancybox="gallery"
data-caption="Optional caption,<br />that contains <em>HTML</em> code"
>
<img src="https://lipsum.app/id/31/300x200" />
</a>
When using Fancybox programmatically, use caption
as the key for the slide object. Example of displaying a gallery:
js
Fancybox.show([
{
src: "https://lipsum.app/id/31/1800x1200",
thumb: "https://lipsum.app/id/31/300x200",
caption: "Sample caption #1",
},
{
src: "https://lipsum.app/id/32/1800x1200",
thumb: "https://lipsum.app/id/32/300x200",
caption: "Sample caption #2",
},
{
src: "https://lipsum.app/id/33/1800x1200",
thumb: "https://lipsum.app/id/33/300x200",
caption: "Sample caption #3",
},
]);
Example of showing only one slide:
js
Fancybox.show([
{
html: "<p>Lorem ipsum dolor sit amet.</p>",
caption: "Sample caption",
},
]);
Customize content
Use a carousel.formatCaption
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:
js
Fancybox.bind("[data-fancybox]", {
Carousel: {
formatCaption: (carouselRef, slide) => {
return `${slide.index + 1} of ${carouselRef.getSlides().length}<br /> ${
slide.caption || ""
}`;
},
},
});
Customize source
If it's more convenient, you can, for example, store the content of the caption in another HTML element. Example:
html
<figure>
<a data-fancybox="gallery" href="https://lipsum.app/id/51/1800x1200">
<img src="https://lipsum.app/id/51/300x200" />
</a>
<figcaption>Sample caption</figcaption>
</figure>
js
Fancybox.bind("[data-fancybox]", {
Carousel: {
formatCaption: (_carouselRef, slide) => {
return slide.triggerEl?.nextElementSibling || "";
},
},
});
ts
Fancybox.bind("[data-fancybox]", {
Carousel: {
formatCaption: (_carouselRef, slide) => {
return (slide.triggerEl?.nextElementSibling as HTMLElement) || "";
},
},
});