Responsive Lightbox Gallery With Pure JavaScript And CSS3 – lightGallery v3

Category: Gallery , Javascript , Modal & Popup , Recommended | October 9, 2026
Authorsachinchoolur
Last UpdateOctober 9, 2026
LicenseMIT
Views33,041 views
Responsive Lightbox Gallery With Pure JavaScript And CSS3 – lightGallery v3

lightGallery v3 is a responsive vanilla JavaScript lightbox library for image and video galleries.

It supports touch navigation, animated transitions, and optional plugins for zoom, thumbnails, and custom gallery layouts.

More Features:

  • Image galleries with touch swipe and desktop mouse dragging.
  • Pinch-to-zoom, double-tap zoom, and swipe-to-close gestures.
  • YouTube, Vimeo, Wistia, and HTML5 video galleries with the video plugin.
  • Animated thumbnails, thumbnail scrubbing, and pagers.
  • Justified thumbnail grids with configurable row height and spacing.
  • Fullscreen viewing, autoplay, rotation, and social sharing through plugins.
  • Dynamic slides and optional thumbnail virtualization for large galleries.
  • Responsive images, captions, deep links, and inline gallery layouts.
  • Keyboard navigation, focus trapping, and customizable control labels.
  • Right-to-left navigation, translated UI text, and custom SVG icons.

How To Use It:

Installation

Install lightgallery from npm for an ES-module project, or load the browser distribution files directly.

lightGallery uses the GPLv3 or a commercial license. GPLv3-compatible open-source projects can request a license key, and proprietary projects require a commercial key. The evaluation key 0000-0000-000-0000 logs a warning and is intended for testing.

Browser Script Setup

Copy the published npm package dist folder into your site and keep its relative file structure. Load the bundled CSS in the document head and load JavaScript before initialization. The bundled CSS includes plugin styles; include the individual plugin JavaScript files for the features you enable.

<!-- In the HTML document head -->
<link rel="stylesheet" href="dist/css/lightgallery-bundle.css">
<!-- Before your gallery initialization code -->
<script src="dist/lightgallery.umd.js"></script>
<script src="dist/plugins/thumbnail/lg-thumbnail.umd.js"></script>
<script src="dist/plugins/zoom/lg-zoom.umd.js"></script>

npm / ES Modules

The npm package exports its core module, plugin modules, CSS assets, and public TypeScript types. Import each plugin explicitly and include its CSS or the bundled stylesheet.

npm install lightgallery
import lightGallery from 'lightgallery';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';
import 'lightgallery/css/lightgallery-bundle.css';
lightGallery(document.getElementById('gallery'), {
  plugins: [lgThumbnail, lgZoom],
  licenseKey: 'your_license_key',
  speed: 400,
});

Markup and Basic Usage

Place anchor elements with full-size image URLs inside a gallery container. Image thumbnails are ordinary <img> elements. data-lg-size records the original image dimensions for the zoom-from-origin animation.

<div id="gallery">
  <a href="images/photo-1-large.jpg" data-lg-size="1600-1067"
     data-sub-html="<h4>Coastal landscape</h4>">
    <img src="images/photo-1-thumb.jpg" alt="Coastal landscape">
  </a>
  <a href="images/photo-2-large.jpg" data-lg-size="1600-1067"
     data-sub-html="<h4>Mountain landscape</h4>">
    <img src="images/photo-2-thumb.jpg" alt="Mountain landscape">
  </a>
</div>

Initialize lightGallery

For the browser-script setup above, initialize after the gallery markup is available. Replace the evaluation key with the correct license key for your project.

const gallery = document.getElementById('gallery');
const instance = lightGallery(gallery, {
  plugins: [lgThumbnail, lgZoom],
  licenseKey: '0000-0000-000-0000',
  speed: 400,
});

More Usage Examples

Justified Gallery Layout

For a justified thumbnail grid, put lg-justified on the gallery container in the HTML. The plugin positions the thumbnails in equal-height rows. Use this markup before the module example:

<div class="lg-justified">
  <a href="images/photo-1-large.jpg" data-lg-size="1600-1067">
    <img src="images/photo-1-thumb.jpg" alt="Coastal landscape">
  </a>
  <a href="images/photo-2-large.jpg" data-lg-size="1600-1067">
    <img src="images/photo-2-thumb.jpg" alt="Mountain landscape">
  </a>
</div>
import lightGallery from 'lightgallery';
import lgJustified from 'lightgallery/plugins/justified';
import 'lightgallery/css/lightgallery-bundle.css';
lightGallery(document.querySelector('.lg-justified'), {
  plugins: [lgJustified],
  licenseKey: 'your_license_key',
  justifiedRowHeight: 180,
  justifiedGap: 8,
  justifiedLastRow: 'start',
  justifiedReveal: 'row',
});

Create a Dynamic Gallery

Dynamic galleries accept an array of slide objects in dynamicEl. An external button can open the gallery at a specified index. In version 3, openGallery(index, element) can use that button as the origin for the opening animation.

<button id="open-gallery" type="button">Open gallery</button>
const trigger = document.getElementById('open-gallery');
const dynamicGallery = lightGallery(trigger, {
  dynamic: true,
  licenseKey: 'your_license_key',
  dynamicEl: [
    { src: 'images/photo-1.jpg', thumb: 'images/thumb-1.jpg', lgSize: '1600-1067' },
    { src: 'images/photo-2.jpg', thumb: 'images/thumb-2.jpg', lgSize: '1600-1067' },
  ],
});
trigger.addEventListener('click', () => dynamicGallery.openGallery(0, trigger));

Large Galleries and Thumbnail Virtualization

Use the gallery markup from Basic Usage. Thumbnail virtualization is optional. slides sets the mounted slide count, and thumbs accepts an overscan count or auto. The thumbnail plugin must be loaded and enabled.

lightGallery(document.getElementById('gallery'), {
  plugins: [lgThumbnail],
  licenseKey: 'your_license_key',
  virtualization: {
    slides: 10,
    thumbs: 'auto',
  },
});

RTL and Translated Controls

Use the gallery markup from Basic Usage. For right-to-left navigation, set direction: 'rtl' and load lg-rtl.css after the main lightGallery CSS. The strings object controls UI labels.

<link rel="stylesheet" href="dist/css/lg-rtl.css">
lightGallery(document.getElementById('gallery'), {
  licenseKey: 'your_license_key',
  direction: 'rtl',
  strings: {
    closeGallery: 'إغلاق المعرض',
    previousSlide: 'الشريحة السابقة',
    nextSlide: 'الشريحة التالية',
  },
});

Video Lightbox

Install the video plugin to show YouTube, Vimeo, Wistia, or HTML5 video slides. For external video providers, videoFacade displays a poster before loading the iframe when a poster is available. The default autoplayFirstVideo: true can load the first player immediately; set it to false when you need click-to-play behavior. This example uses a YouTube slide with a poster:

<div id="video-gallery">
  <a href="https://www.youtube.com/watch?v=aqz-KE-bpKQ"
     data-poster="images/video-poster.jpg">
    <img src="images/video-thumbnail.jpg" alt="Video preview">
  </a>
</div>
import lightGallery from 'lightgallery';
import lgVideo from 'lightgallery/plugins/video';
import 'lightgallery/css/lightgallery-bundle.css';
lightGallery(document.getElementById('video-gallery'), {
  plugins: [lgVideo],
  licenseKey: 'your_license_key',
  videoFacade: true,
  autoplayFirstVideo: false,
  youTubeNoCookie: true,
});

Configuration Options

Core options apply to every gallery. Plugin options require the relevant plugin constructor. The defaults refer to lightGallery 3.0.0. strings merges per key; mobileSettings uses its own values and does not inherit missing desktop settings.

Core: Animation, Layout, and Appearance

Option / defaultDescription
addClass (string)
Default: ”
Extra CSS class on the gallery container.
allowMediaOverlap (boolean)
Default: false
Permit controls, captions, and thumbnails to overlap the media.
appendCounterTo (string)
Default: ‘.lg-toolbar’
Selector for the slide counter container.
appendSubHtmlTo (selector)
Default: ‘.lg-sub-html’
Caption container: .lg-sub-html, .lg-item, or .lg-outer.
backdropDuration (number)
Default: 300
Backdrop transition in milliseconds.
container (element / selector / function)
Default: ”
Parent container for the gallery; defaults to the document body.
direction (‘ltr’ / ‘rtl’ / ‘auto’)
Default: ‘ltr’
Reading and navigation direction; RTL styling requires lg-rtl.css.
easing (string)
Default: ‘ease’
CSS transition easing.
height (string)
Default: ‘100%’
Gallery height.
icons (object)
Default: {}
Custom SVG markup keyed by control icon name.
mode (string)
Default: ‘lg-slide’
Slide animation class, including lg-fade and the 31 values shown below.
nextHtml (string)
Default: ”
Custom next-arrow HTML.
prevHtml (string)
Default: ”
Custom previous-arrow HTML.
showBarsAfter (number)
Default: 10000
First-open delay affecting control bar visibility, in milliseconds.
slideDelay (number)
Default: 0
Delay before a slide transition, in milliseconds.
speed (number)
Default: 400
Slide transition duration, in milliseconds.
startAnimationDuration (number)
Default: 400
Opening zoom animation duration, in milliseconds.
startClass (string)
Default: ‘lg-start-zoom’
Opening animation class when zoomFromOrigin does not take precedence.
strings (object)
Default: see below
Translated toolbar labels, errors, and announcements; merges by key.
videoMaxSize (string)
Default: ‘1280-720’
Default maximum video dimensions.
width (string)
Default: ‘100%’
Gallery width.
zoomFromOrigin (boolean)
Default: true
Animate opening from the image thumbnail when image dimensions are available.

Core: Navigation and Interaction

Option / defaultDescription
ariaAnnouncements (boolean)
Default: true
Announce slide changes through a polite live region.
ariaDescribedby (string)
Default: ”
Gallery aria-describedby reference.
ariaLabelledby (string)
Default: ”
Gallery aria-labelledby reference.
closable (boolean)
Default: true
Permit the gallery to close.
closeOnTap (boolean)
Default: true
Close when the backdrop is tapped.
controls (boolean)
Default: true
Display previous and next controls.
counter (boolean)
Default: true
Display slide index and total.
download (boolean)
Default: true
Show the download control.
enableDrag (boolean)
Default: true
Enable desktop drag navigation.
enableSwipe (boolean)
Default: true
Enable touch swipe navigation.
escKey (boolean)
Default: true
Allow Escape to close the gallery.
flickVelocity (number)
Default: 0.5
Swipe-release velocity threshold in pixels per millisecond.
getCaptionFromTitleOrAlt (boolean)
Default: true
Derive captions from title or alt attributes.
hideBarsDelay (number)
Default: 0
Time in milliseconds before hiding controls; zero prevents auto-hide.
hideControlOnEnd (boolean)
Default: false
Hide inactive edge arrow; ignored when looping or edge animation is active.
hideScrollbar (boolean)
Default: false
Hide the document scrollbar while open.
keyPress (boolean)
Default: true
Enable keyboard controls.
loop (boolean)
Default: true
Loop from last slide to first and back.
mousewheel (boolean)
Default: false
Enable wheel-based slide navigation.
pinchToClose (boolean)
Default: true
Close an unzoomed image using a pinch gesture when zoom plugin is active.
showCloseIcon (boolean)
Default: true
Display the close control.
showGestureButtons (boolean)
Default: true
Display toolbar controls that mirror gestures; disabled in mobile defaults.
showMaximizeIcon (boolean)
Default: false
Display maximize control for inline galleries.
slideEndAnimation (boolean)
Default: true
Animate a swipe at gallery boundaries.
subHtmlSelectorRelative (boolean)
Default: false
Resolve caption selectors relative to each trigger element.
swipeThreshold (number)
Default: 50
Minimum swipe distance in pixels.
swipeToClose (boolean)
Default: true
Enable vertical swipe to close.
toolbarOverflow (boolean)
Default: true
Move excess toolbar controls into a More options menu.
trapFocus (boolean)
Default: true
Keep keyboard focus inside the open gallery.

Core: Media, Loading, and Data

Option / defaultDescription
defaultCaptionHeight (number)
Default: 0
Caption height used to position media when overlap is disabled.
dynamic (boolean)
Default: false
Use JavaScript-provided gallery items.
dynamicEl (GalleryItem[])
Default: []
Array of slides for a dynamic gallery.
exThumbImage (string)
Default: ”
Custom data attribute supplying thumbnail URLs.
extraProps (string[])
Default: []
Additional item properties to read from attributes.
iframeHeight (string)
Default: ‘100%’
Iframe height.
iframeMaxHeight (string)
Default: ‘100%’
Iframe maximum height.
iframeMaxWidth (string)
Default: ‘100%’
Iframe maximum width.
iframeWidth (string)
Default: ‘100%’
Iframe width.
index (number)
Default: 0
Initially selected slide (zero-based).
isMobile (function)
Default: undefined
Override mobile device detection.
licenseKey (string)
Default: ‘0000-0000-000-0000’
GPLv3 or commercial license key; placeholder is evaluation-only.
loadYouTubePoster (boolean)
Default: true
Load a YouTube poster image automatically.
mobileSettings (object)
Default: see below
Mobile-specific controls and toolbar defaults.
numberOfSlideItemsInDom (number)
Default: 10
Mounted slide window size, minimum 3.
plugins (function[])
Default: []
Explicit plugin constructors for each gallery.
preload (number)
Default: 2
Number of adjacent slides to preload after current image loads.
resetScrollPosition (boolean)
Default: true
Restore the earlier page scroll position on close.
selector (selector / collection)
Default: ”
Select media elements beyond direct children.
selectWithin (string)
Default: ”
Limit custom media selector lookup to another container.
virtualization (object)
Default: undefined
Optional slide and thumbnail windowing for large galleries.

Virtualization Options

Set virtualization to an object to override the slide pool size or enable a windowed thumbnail strip. The top-level setting is disabled by default.

PropertyMeaning
slidesMounted-slide count. Overrides numberOfSlideItemsInDom when set.
thumbsThumbnail overscan per side as a number, or auto for one extra viewport per side. Omit the property to keep the complete thumbnail strip.

Accepted Animation Modes

The mode option accepts the following CSS transition names. These are exact option values.

'lg-slide'
'lg-fade'
'lg-zoom-in'
'lg-zoom-in-big'
'lg-zoom-out'
'lg-zoom-out-big'
'lg-zoom-out-in'
'lg-zoom-in-out'
'lg-soft-zoom'
'lg-scale-up'
'lg-slide-circular'
'lg-slide-circular-vertical'
'lg-slide-vertical'
'lg-slide-vertical-growth'
'lg-slide-skew-only'
'lg-slide-skew-only-rev'
'lg-slide-skew-only-y'
'lg-slide-skew-only-y-rev'
'lg-slide-skew'
'lg-slide-skew-rev'
'lg-slide-skew-cross'
'lg-slide-skew-cross-rev'
'lg-slide-skew-ver'
'lg-slide-skew-ver-rev'
'lg-slide-skew-ver-cross'
'lg-slide-skew-ver-cross-rev'
'lg-lollipop'
'lg-lollipop-rev'
'lg-rotate'
'lg-rotate-rev'
'lg-tube'

Core Nested Defaults

The strings object accepts the public labels below and merges your overrides with the defaults. The mobileSettings object has its own defaults.

const gallerySettings = {
  mobileSettings: {
    controls: false,
    showCloseIcon: false,
    download: false,
    showGestureButtons: false,
  },
  strings: {
    closeGallery: 'Close gallery',
    toggleMaximize: 'Toggle maximize',
    previousSlide: 'Previous slide',
    nextSlide: 'Next slide',
    download: 'Download',
    playVideo: 'Play video',
    mediaLoadingFailed: 'Oops... Failed to load content...',
    galleryLabel: 'Gallery',
    slideAnnouncement: 'Image {index} of {total}',
    moreOptions: 'More options',
    share: 'Share',
    toggleThumbnails: 'Toggle thumbnails',
    toggleAutoplay: 'Toggle Autoplay',
    toggleFullscreen: 'Toggle Fullscreen',
    zoomIn: 'Zoom in',
    zoomOut: 'Zoom out',
    viewActualSize: 'View actual size',
    rotateLeft: 'Rotate left',
    rotateRight: 'Rotate right',
    flipHorizontal: 'Flip horizontal',
    flipVertical: 'Flip vertical',
    toggleComments: 'Toggle Comments',
  }
};

SVG Icon Override Names

The icons option accepts SVG markup keyed by these control names. Unspecified icons retain their defaults. Supply both names for maximize/minimize, autoplay play/pause, and fullscreen enter/exit state pairs.

GroupIcon names
Core controlsclose, prev, next, download, more, maximize, minimize
Zoom and image controlszoomIn, zoomOut, actualSize (framework static icon; unused by the default vanilla UI), rotateLeft, rotateRight, flipHorizontal, flipVertical
Sharingshare, shareFacebook, shareX, sharePinterest
Playback and fullscreenautoplayPlay, autoplayPause, fullscreen, fullscreenExit
Comments and thumbnailscomment, commentClose, toggleThumbnails

Plugin Settings

Each group applies only when its plugin is imported or loaded and included in the plugins array. Deprecated per-plugin translation objects are included as compatibility aliases; strings is the current localization setting.

Zoom Plugin

Option / defaultDescription
actualSize (boolean)
Default: true
Show the actual-size button.
actualSizeIcons (object)
Default: {zoomIn:’lg-zoom-in’,zoomOut:’lg-zoom-out’}
CSS class names for actual-size zoom states.
enableZoomAfter (number)
Default: 300
Delay in milliseconds before enabling zoom effects.
infiniteZoom (boolean)
Default: true
Allow zoom levels beyond image native dimensions.
scale (number)
Default: 1
Zoom increment and decrement scale.
showZoomInOutIcons (boolean)
Default: false
Display explicit zoom-in and zoom-out buttons.
zoom (boolean)
Default: true
Enable zoom interactions.
zoomPluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.

Thumbnail Plugin

Option / defaultDescription
alignThumbnails (‘left’ / ‘middle’ / ‘right’)
Default: ‘middle’
Alignment for short thumbnail rows.
animateThumb (boolean)
Default: true
Animate the thumbnail strip.
appendThumbnailsTo (selector)
Default: ‘.lg-components’
Thumbnail container: .lg-components or .lg-outer.
currentPagerPosition (‘left’ / ‘middle’ / ‘right’)
Default: ‘middle’
Position of the selected thumbnail.
enableThumbDrag (boolean)
Default: true
Enable mouse dragging of thumbnails.
enableThumbSwipe (boolean)
Default: true
Enable touch dragging of thumbnails.
loadYouTubeThumbnail (boolean)
Default: true
Load thumbnails from YouTube.
scrubThumbnails (boolean)
Default: false
Scrub slides directly as the thumbnail strip moves.
thumbHeight (string)
Default: ’80px’
Height of each thumbnail.
thumbMargin (number)
Default: 5
Thumbnail spacing.
thumbnail (boolean)
Default: true
Enable thumbnail UI.
thumbnailPluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.
thumbnailSwipeThreshold (number)
Default: 10
Minimum thumbnail drag distance in pixels.
thumbWidth (number)
Default: 100
Width of each thumbnail.
toggleThumb (boolean)
Default: false
Allow thumbnail toggle control when the layout permits.
youTubeThumbSize (number)
Default: 1
YouTube thumbnail image size selector.

Justified Layout Plugin

Option / defaultDescription
justified (boolean)
Default: true
Enable justified trigger grid; requires a static gallery with lg-justified class.
justifiedGap (number)
Default: 8
Gap between items and rows in pixels.
justifiedLastRow (‘justify’ / ‘start’ / ‘hide’)
Default: ‘start’
Layout of incomplete final row.
justifiedMaxScale (number)
Default: 1.75
Maximum row height multiplier.
justifiedReveal (‘row’ / ‘image’)
Default: ‘row’
Reveal by completed rows or individual loaded images.
justifiedRowHeight (number)
Default: 180
Intended row height in pixels.

Video Plugin

Option / defaultDescription
autoplayFirstVideo (boolean)
Default: true
Automatically play the first video slide.
autoplayVideoOnSlide (boolean)
Default: false
Autoplay a video when its slide becomes active.
gotoNextSlideOnVideoEnd (boolean)
Default: true
Go to the next slide when the current video ends; provider behavior varies.
videoFacade (boolean)
Default: true
Delay external provider iframe creation until playback starts when a poster is available.
videojs (boolean)
Default: false
Enable video.js player integration when its dependency is loaded.
videojsOptions (object)
Default: {}
Options forwarded to video.js.
videojsTheme (string)
Default: ”
Custom video.js theme class; include theme CSS.
vimeoPlayerParams (object / false)
Default: false
Vimeo player settings.
wistiaPlayerParams (object / false)
Default: false
Wistia player settings.
youTubeNoCookie (boolean)
Default: true
Prefer youtube-nocookie.com for embedded YouTube videos.
youTubePlayerParams (object / false)
Default: false
YouTube player settings.

Hash Plugin

Option / defaultDescription
customSlideName (boolean)
Default: false
Enable custom slide names in gallery URLs.
galleryId (string)
Default: ‘1’
Unique gallery identifier for multiple hash-enabled instances.
hash (boolean)
Default: true
Enable deep links and browser history integration.
hashDriver (‘auto’ / ‘history’ / ‘navigation’)
Default: ‘auto’
Choose URL sync driver and fallback behavior.

Autoplay Plugin

Option / defaultDescription
appendAutoplayControlsTo (string)
Default: ‘.lg-toolbar’
Autoplay controls parent selector.
autoplay (boolean)
Default: true
Enable autoplay plugin controls and logic.
autoplayControls (boolean)
Default: true
Display autoplay controls.
autoplayPluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.
forceSlideShowAutoplay (boolean)
Default: false
Keep slideshow autoplay active after interaction.
progressBar (boolean)
Default: true
Display slide countdown progress bar.
slideShowAutoplay (boolean)
Default: false
Start automatic slideshow playback.
slideShowInterval (number)
Default: 5000
Time between automatic slides in milliseconds, counted after loading.

Rotate Plugin

Option / defaultDescription
flipHorizontal (boolean)
Default: true
Enable horizontal flip.
flipVertical (boolean)
Default: true
Enable vertical flip.
rotate (boolean)
Default: true
Enable rotation controls.
rotateLeft (boolean)
Default: true
Show counterclockwise rotation.
rotatePluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.
rotateRight (boolean)
Default: true
Show clockwise rotation.
rotateSpeed (number)
Default: 400
Rotation duration in milliseconds.

Share Plugin

Option / defaultDescription
additionalShareOptions (ShareOption[])
Default: []
Custom share destinations.
facebook (boolean)
Default: true
Enable Facebook sharing.
facebookDropdownText (string)
Default: ‘Facebook’
Label for Facebook item.
pinterest (boolean)
Default: true
Enable Pinterest sharing.
pinterestDropdownText (string)
Default: ‘Pinterest’
Label for Pinterest item.
preferNativeShare (boolean)
Default: device-dependent
Use navigator.share on eligible touch devices and a dropdown fallback.
share (boolean)
Default: true
Enable share controls.
sharePluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.
twitter (boolean)
Default: true
Enable X sharing via legacy twitter option.
twitterDropdownText (string)
Default: ‘X’
Visible label for X share item.

Custom Share Destination Fields

Each object in additionalShareOptions uses the public ShareOption fields.

PropertyMeaning
selectorCSS selector used for the custom share item.
dropdownHTMLHTML markup inserted for the share item.
generateLink(galleryItem)Callback returning a share destination URL for the current gallery item.

Pager Plugin

Option / defaultDescription
pager (boolean)
Default: true
Enable dots/pager navigation.

Fullscreen Plugin

Option / defaultDescription
fullScreen (boolean)
Default: true
Enable native fullscreen control.
fullscreenPluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.

Comment Box Plugin

Option / defaultDescription
commentBox (boolean)
Default: false
Enable comments UI.
commentPluginStrings (object)
Default: deprecated
Legacy translation alias; use core strings.
commentsMarkup (string)
Default: built-in HTML
Custom comments markup.
disqusComments (boolean)
Default: false
Enable Disqus comments.
disqusConfig (object)
Default: {title:undefined,language:’en’}
Disqus configuration.
fbComments (boolean)
Default: false
Enable Facebook comments.

Medium Zoom Plugin

Option / defaultDescription
backgroundColor (string)
Default: ‘#000’
Background color; per-slide data-lg-background-color can override.
margin (number)
Default: 40
Space around the displayed image.
mediumZoom (boolean)
Default: true
Enable Medium-style zoom.

Vimeo Thumbnail Plugin

Option / defaultDescription
showThumbnailWithPlayButton (boolean)
Default: false
Draw a play button over video thumbnails.
showVimeoThumbnails (boolean)
Default: true
Load Vimeo video thumbnails automatically.

Relative Caption Plugin

Option / defaultDescription
relativeCaption (boolean)
Default: false
Position captions relative to displayed media.

Origin Crop Plugin

Option / defaultDescription
originCrop (boolean)
Default: true
Expand cropped cover-fit thumbnails from their visible image region.

Methods

lightGallery(element, options?) returns the gallery instance. The public lightGallery.setLicenseKey(key) method sets a shared key before galleries initialize. Call instance methods on that returned object, or read it from lgInit. Indices are zero-based. For an open gallery, pass a new item array to updateSlides; use refresh after changing closed-gallery markup.

Public MethodBehavior
lightGallery.setLicenseKey(key)Set a shared license key before initializing galleries. An individual gallery’s licenseKey option takes precedence.
lightGallery(element, options?)Initialize a gallery on an HTML element and return its instance. The options object is optional.
instance.slide(index)Navigate to the zero-based slide index.
instance.goToNextSlide()Navigate to the following slide.
instance.goToPrevSlide()Navigate to the preceding slide.
instance.openGallery(index?, element?)Open at a slide index. Version 3 accepts an origin element for dynamic-gallery opening.
instance.closeGallery(force?)Close an open gallery. Pass true to force close when closable is false.
instance.refresh(items?)Refresh gallery after markup changes; pass replacement dynamic items in dynamic mode.
instance.updateSlides(items, index)Replace items while the gallery is open and set the current slide index.
instance.toggleMaximize()Switch an inline gallery between minimized and maximized views.
instance.destroy()Destroy the gallery and its plugins, close it if needed, and return the teardown duration in milliseconds. Reinitialize only after teardown finishes.

Event Handlers

Register listeners on the gallery element before calling lightGallery(), especially for lgInit. Event payloads use event.detail.

const element = document.getElementById('gallery');
element.addEventListener('lgBeforeSlide', (event) => {
  console.log(event.detail.prevIndex, event.detail.index);
});
element.addEventListener('lgInit', (event) => {
  console.log(event.detail.instance);
});
lightGallery(element, { licenseKey: 'your_license_key' });
Custom EventWhen Fired / Details
lgInitOnce on initialization; detail.instance gives the instance.
lgBeforeOpenImmediately before opening.
lgAfterOpenImmediately after opening.
lgAfterAppendSlideAfter slide markup is inserted; detail.index.
lgAfterAppendSubHtmlAfter caption content is appended; detail.index.
lgSlideItemLoadAfter a slide media item loads or fails and the error state settles; detail.index, detail.delay, detail.isFirstSlide.
lgHasVideoWhen a video slide is detected; detail.hasPoster, detail.html5Video, detail.index, detail.src.
lgBeforeSlideBefore transition; detail.prevIndex, detail.index, detail.fromTouch, detail.fromThumb.
lgAfterSlideAfter transition; detail.prevIndex, detail.index, detail.fromTouch, detail.fromThumb.
lgBeforeNextSlideBefore next-slide transition; detail.index, detail.fromTouch.
lgBeforePrevSlideBefore previous-slide transition; detail.index, detail.fromTouch.
lgPosterClickOn video poster click.
lgDragStartWhen slide dragging begins.
lgDragMoveDuring slide dragging.
lgDragEndWhen slide dragging ends.
lgContainerResizeWhen the gallery container resizes; detail.index.
lgBeforeCloseBefore closing starts.
lgAfterCloseAfter closing; detail.instance.
lgRotateLeftAfter counterclockwise rotation; detail.index.
lgRotateRightAfter clockwise rotation; detail.index.
lgFlipHorizontalAfter horizontal flip; detail.index.
lgFlipVerticalAfter vertical flip; detail.index.
lgAutoplayEmitted when the autoplay plugin advances the slideshow.
lgAutoplayStartEmitted when autoplay starts.
lgAutoplayStopEmitted when autoplay stops.

HTML Attributes and Data Attributes

The normal anchor href contains the full-size file URL. The data-* attributes extend each slide. Plugin-specific attributes require the matching plugin.

AttributeMeaning
altImage alternative text, usually on the thumbnail image.
titleBrowser title text; lightGallery can use it for captions.
data-lg-sizeOriginal image width-height used by zoom-from-origin, for example 1600-1067.
data-srcMain slide image, video, or other media URL.
data-responsiveResponsive image URL and width pairs.
data-srcsetMain image srcset string.
data-sizesSizes for responsive srcset selection.
data-sourcesPicture element source definitions.
data-sub-htmlCaption markup or selector for caption element.
data-sub-html-urlURL of external caption content.
data-posterPoster URL for video slides.
data-videoJSON-like HTML5 video source configuration.
data-iframeSet true for an iframe slide.
data-iframe-titleIframe title for accessibility.
data-downloadPreferred downloaded file name.
data-download-urlSlide download URL, or false to hide this download.
data-slide-nameCustom deep-link slide name with hash plugin.
data-widthNative image width for zoom calculation.
data-disqus-identifierDisqus identifier.
data-disqus-urlDisqus URL.
data-fb-htmlFacebook comments HTML.
data-facebook-share-urlPer-slide Facebook URL.
data-pinterest-share-urlPer-slide Pinterest URL.
data-pinterest-textPinterest text.
data-twitter-share-urlPer-slide X/Twitter URL; legacy attribute name.
data-tweet-textPer-slide X/Twitter share text; legacy attribute name.
data-lg-background-colorMedium zoom slide background color.
data-*Custom thumbnail URL attribute configured through exThumbImage.

Dynamic Gallery Item Properties

Each object in dynamicEl uses camelCase rather than data-* names. lgSize is available for version 3 origin animation; the following public values correspond to the attribute-based slide fields.

Item PropertyPurpose
srcFull-size media URL.
thumbThumbnail URL.
lgSizeOriginal image dimensions, for example 1600-1067.
altImage alternative text.
titleTitle text.
responsiveResponsive image URL and width pairs.
srcsetResponsive srcset definition.
sizesImage sizes attribute.
sourcesPicture source definitions.
subHtmlHTML caption or caption element selector.
subHtmlUrlExternal caption URL.
posterVideo poster URL.
videoHTML5 video source object.
iframeTrue to use an iframe.
iframeTitleIframe title.
downloadSuggested download name.
downloadUrlDownload URL, or false to disable.
slideNameDeep-link slide name.
widthIntrinsic image width.
disqusIdentifierDisqus identifier.
disqusUrlDisqus URL.
fbHtmlFacebook comments markup.
facebookShareUrlFacebook URL.
pinterestShareUrlPinterest URL.
pinterestTextPinterest text.
twitterShareUrlX/Twitter URL (legacy property name).
tweetTextX/Twitter share text (legacy property name).
shareUrlShared link used by native sharing in version 3.

Sass Variables

Use these Sass variables when customizing the gallery theme through @use and @forward. The compiled CSS does not expose them as runtime CSS custom properties. $lg-thumb-container-height is declared without !default and cannot be overridden through Sass @use ... with.

Sass VariableDefault / Purpose
$backdrop-opacity1 | Backdrop opacity.
$lg-toolbar-bglinear-gradient(…) | Toolbar background gradient.
$lg-border-radius-base2px | Base border radius.
$lg-theme-highlightrgb(169, 7, 7) | Highlight color.
$lg-theme-color#000 | Base theme color.
$lg-icon-bgrgba(0,0,0,0.45) | Control icon background.
$lg-icon-color#999 | Icon foreground.
$lg-icon-hover-color#fff | Hovered icon color.
$lg-counter-color#e6e6e6 | Counter color.
$lg-counter-font-size16px | Counter font size.
$lg-next-prev-bg$lg-icon-bg | Navigation icon background.
$lg-next-prev-color$lg-icon-color | Navigation icon color.
$lg-next-prev-hover-color$lg-icon-hover-color | Hovered navigation icon color.
$lg-toolbar-icon-color$lg-icon-color | Toolbar icon color.
$lg-toolbar-icon-hover-color$lg-icon-hover-color | Hovered toolbar icon color.
$lg-toolbar-icon-disabled-opacity0.75 | Disabled toolbar control opacity.
$lg-progress-bar-bg#333 | Autoplay progress track.
$lg-progress-bar-active-bg$lg-theme-highlight | Autoplay progress fill.
$lg-progress-bar-height5px | Autoplay progress height.
$lg-path-images‘../images’ | Relative asset directory.
$zoom-transition-duration0.5s | Zoom transition duration.
$lg-sub-html-bglinear-gradient(…) | Caption background gradient.
$lg-sub-html-color#eee | Caption text color.
$lg-thumb-toggle-bg#0d0a0a | Thumbnail toggle background.
$lg-thumb-toggle-color$lg-icon-color | Thumbnail toggle color.
$lg-thumb-bg#0d0a0a | Thumbnail strip background.
$lg-thumb-container-height100px | Thumbnail container height; source variable has no !default declaration.
$zindex-outer1050 | Gallery container stacking order.
$zindex-progressbar1083 | Progress bar stacking order.
$zindex-controls1084 | Navigation controls stacking order.
$zindex-toolbar1082 | Toolbar stacking order.
$zindex-subhtml1080 | Caption stacking order.
$zindex-components1080 | Component stacking order.
$zindex-pager1080 | Pager stacking order.
$zindex-playbutton1080 | Video play button stacking order.
$zindex-item1060 | Slide item stacking order.
$zindex-backdrop1040 | Backdrop stacking order.

Migrating From Version 2

  • The vanilla lightGallery(element, options) API and separate plugin imports are retained.
  • JavaScript projects use the lightgallery package. Framework wrappers move to @lightgallery/react, @lightgallery/vue, and @lightgallery/angular.
  • Version 3 commercial license keys start with LIG.
  • The former supportLegacyBrowser setting and its polyfill behavior are removed.
  • Icon font files are removed; toolbar icons use inline SVG. Customize them with icons.
  • Plugin-specific translation objects are deprecated. Set translations through the core strings object.
  • Sass customization uses @use and @forward. Review projects that override SCSS variables.
  • Video poster facades, toolbar overflow, and new gesture behavior change default presentation. Adjust videoFacade, toolbarOverflow, and related settings if necessary.

Alternatives & Related Resources

FAQs:

Q: Why do the thumbnail and zoom controls not appear?
A: Import or load the corresponding plugin JavaScript, include its constructor in plugins, and load either its CSS file or lightgallery-bundle.css.

Q: Why does the first video iframe load before the visitor presses Play?
A: autoplayFirstVideo defaults to true. Set it to false when you want the videoFacade poster to remain in place until playback.

Q: Why does lgInit not fire in my event listener?
A: Register the listener on the gallery element before calling lightGallery(). Initialization emits the event immediately.

Q: Can I update a gallery after new images have loaded?
A: Use instance.refresh() after editing a closed gallery’s markup. Use instance.updateSlides(items, index) with a new item array when the gallery is open.

Changelog:

v3.0.0 (October 9, 2026)

  • New justified layout and origin crop plugins.
  • Native framework packages and a shared headless core.
  • Virtualization, video facades, thumbnail scrubbing, and custom SVG icons.
  • RTL navigation, unified localization strings, Web Share, and new accessibility controls.
  • Improved mobile gestures, toolbar overflow, and video loading.
  • Removed legacy polyfills, icon fonts, and old framework wrappers.

v2.9.0 (October 1, 2025)

  • Sass styles migrated from @import to @use / @forward.
  • Zoom-plugin bug fix.

v2.8.3 (03/01/2025)

  • Remove unnecessary debug log

v2.8.2 (11/28/2024)

  • Bugfix

v2.8.1 (11/13/2024)

  • refactor(container): add type () => HTMLElement & string selector support
  • bugfixes

v2.7.2 (09/20/2023)

  • Add alt tag for thumbnails if available
  • Infinite zoom (Zoom beyond actual size) support
  • enable the close button on mobile for iframe
  • fix(zoom): zoom in and out not happening when clicked too fast
  • feat(strings): make error message customizable

v2.7.1 (01/11/2023)

  • Support for YouTube nocookie
  • Bugfixes

v2.7.0 (10/09/2022)

  • Add support for angular 13 and 14
  • Big fix – Zoom button is disabled when clicking too fast

v2.6.1 (09/14/2022)

  • Bug fix – grayed zoom icon

v2.6.0 (08/29/2022)

  • Refactor zoom module
  • Fix issue – Blurry images when zooming on iOS devices
  • Make lightGallery compatible with react 18 strict mode
  • Next / previous button not working with overlapping caption

v2.5.0 (06/13/2022)

  • New VimeoThumbnail plugin that automatically loads thumbnail for Vimeo videos
  • Private video support for Vimeo videos
  • Videojs custom theme support
  • Trap focus within lightGallery
  • Option to hide the scrollbar
  • Option to skip scrolling back to the original position on close
  • Bug fixes

v2.4.0 (01/29/2022)

  • Add i18n support
  • Add rotate callback for Angular, React, and Vue components
  • Add events for autoplay actions autoplay, autoplayStart and autoplayStop
  • Bug Fixes

v2.3.0 (10/28/2021)

  • Add URL params support for YouTube videos.
  • Add URL parameters support for Vimeo videos
  • Improve video autoplay experience
  • Automatically load poster images for youtube videos
  • Add iframe max-width max-height options
  • Removed showAfterLoad option as it is already managed via startClass
  • Bug fixes/improvements

v2.2.1 (09/05/2021)

  • Fixed: Mixed content Uncaught TypeError

v2.2.0 (08/20/2021)

  • Make rotate speed configurable via rotateSpeed option
  • Emit events on rotate and flip
  • Add video tracks support
  • Add an option set name for the downloaded file
  • Add an option to append captions to the outer div. By setting appendSubHtmlTo to .lg-outer, the main gallery portion and captions can be placed side by side
  • Bugs fixed
  • This release changes the HTML structure a little bit – class .lg has been renamed to .lg-content and lg-inner and controls have been moved inside .lg-content. This will affect your existing setup only if you have made any customization
  • Download button for video and iframes slides is not disabled by default. You need explicitly pass data-download-url=”false” if you need to disable the download button.
  • Settings width and height have been removed

v2.1.8 (07/08/2021)

  • Bug fixes and improvements

v2.1.7 (06/30/2021)

  • Bug fixes

v2.1.6 (06/29/2021)

  • Bugfix: Wrong button gets disabled on first and last images in gallery (Previous instead of Next)

v2.1.5 (06/12/2021)

  • New relativeCaptions plugin to place captions relative to the media

v2.1.4 (06/11/2021)

  • Fixed: Srcset segments will be converted to html attributes

v2.1.3 (06/07/2021)

  • Fixed: The image is shifted under certain circumstances

v2.1.2 (06/06/2021)

  • Add lit component support
  • Bugfix – Fix setting selector type

v2.1.1 (06/02/2021)

  • Bug fixes

v2.1.0 (05/28/2021)

  • Add refresh method
  • Allow plugins to modify core settings
  • New plugin for medium like zoom experience
  • Add elementClassNames prop for react component
  • Bug fixes

v2.0.0 (05/25/2021)

  • Completely re-wrote from scratch in typescript
  • Removed jQuery dependency
  • Available for React, Vue.js, and Angular
  • Moved all modules to the main repo for better maintainability
  • Dropped IE 8 and 9 support. Let me know if you still need support for IE 8 and 9. I’ll consider adding a plugin to add support if there is enough demand
  • Separated plugin and transitions CSS from the core CSS file
  • Pinch to zoom
  • Virtual slides
  • Swipe to close
  • Zoom from the origin
  • Inline gallery
  • Next-generation image formats support(webp, JPEG XL). etc
  • Better customizability
  • Better performance on mobile devices.
  • Dynamically add, remove slides while the gallery is open
  • Comment interface
  • and much more.

v1.4.1beta (10/29/2020)

  • Fix vimeo embed url in gallery

v1.4.0 (10/14/2020)

  • Add option to turn off hiding toolbar and controls
  • Add supportLegacyBrowser option
  • Better error messaging
  • Minor bug fixes

v1.3.1 (09/19/2020)

  • Fix issue – Horizontal and vertical flip buttons class names are interchanged

v1.3.0 (09/01/2020)

  • Add rotate module

v1.2.1 (08/18/2020)

  • Remove unnecessary outline from the outer element.

v1.2.0 (07/29/2020)

  • Accessibility improvements

v1.1.1 (09/03/2018)

  • lg-thumbnail bug fix

You Might Be Interested In:


3 thoughts on “Responsive Lightbox Gallery With Pure JavaScript And CSS3 – lightGallery v3”

  1. Daniel

    Great Lightbox! Just one question: How do I add several images to a slideshow while having only one thumbnail?
    I’d really appreciate some help :-)

    Reply ↓
  2. wy07

    Love the Lightbox! May I know how to create more than 1 gallery in a single page on WordPress? Am using tabs so each tab will have one gallery. Look forward to your reply. Thank you.

    Reply ↓

Leave a Reply