Skip to content
On this page

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:

html
<a
  href="image-a.jpeg"
  data-fancybox="gallery"
  data-caption="Optional caption,&lt;br /&gt;that contains &lt;em&gt;HTML&lt;/em&gt; code"
>
  <img src="thumbnail-a.jpeg" />
</a>

When using Fancybox programmatically, use the caption as the key for the slide object:

js
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:

js
Fancybox.bind("[data-fancybox]", {
  caption: (fancybox, slide) => {
    const caption = slide.caption || "";

    return `${slide.index + 1} / ${
      fancybox.carousel?.slides.length
    } <br /> ${caption}`;
  },
});

JSFiddle Example

Different source

If it's more convenient, you can, for example, store the content of the caption in another HTML element. Example:

html
<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>
js
Fancybox.bind("[data-fancybox]", {
  caption: function (fancybox, slide) {
    const figurecaption = slide.triggerEl?.querySelector("figurecaption");
    return figurecaption ? figurecaption.innerHTML : slide.caption || "";
  },
});

JSFiddle Example

If you want to use the alt attribute of the thumbnails as caption content, that's easy:

js
Fancybox.bind("[data-fancybox]", {
  caption: function (fancybox, slide) {
    return slide.thumbEl?.alt || "";
  },
});

JSFiddle Example

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:

css
.fancybox__slide.has-caption {
  flex-direction: row;
}

.fancybox__caption {
  max-width: 250px;
  padding: 1rem 3rem 1rem 1rem;
}

JSFiddle Example