Bootstrap 5 Gallery With Lightbox

Bootstrap 5 Gallery With Lightbox
Code Snippet:Bootstrap 5 Lightbox Gallery
Author: Adorade
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 4,887
License: MIT
Edit Code online: View on CodePen
Read More

This code is a Bootstrap 5-based gallery with a lightbox feature. It displays a collection of images in a grid layout. When you click on an image, it opens in a full-screen lightbox, allowing you to view the images one by one. The lightbox provides navigation controls to move between images.

The primary functionality of this code is to create an interactive image gallery with a lightbox feature. It’s helpful for showcasing a set of images and enhancing the user experience by allowing them to view images in a larger format without leaving the current page.

How to Create Bootstrap 5 Gallery With Lightbox

1. First of all, create an HTML file and include the necessary Bootstrap 5 and JavaScript dependencies. You can include these dependencies using CDN links.

<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css'>
<script src='https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js'></script>

2. Inside the <body> of your HTML file, create the gallery structure. You can customize the gallery by adding your own images and captions as needed. Here’s an example:

<h1 class="text-center mb-0">Bootstrap 5 Lightbox Gallery</h1>
<p class="text-center mb-4">Click an image to reveal the lightbox</p>

<section class="photo-gallery">
  <div class="container">
    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4 gallery-grid">
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/251/1200/800.webp">
          <img src="https://picsum.photos/id/251/480/320.webp" class="img-fluid" alt="Lorem ipsum dolor sit amet">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/678/1200/800.webp">
          <img src="https://picsum.photos/id/678/480/320.webp" class="img-fluid" alt="Ipsum lorem dolor sit amet">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/74/1200/800.webp">
          <img src="https://picsum.photos/id/74/480/320.webp" class="img-fluid" alt="Dolor lorem ipsum sit amet">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/92/1200/800.webp">
          <img src="https://picsum.photos/id/92/480/320.webp" class="img-fluid" alt="Sit amet lorem ipsum dolor">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/62/1200/800.webp">
          <img src="https://picsum.photos/id/62/480/320.webp" class="img-fluid" alt="Aut ipsam deserunt nostrum quo">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/575/1200/800.webp">
          <img src="https://picsum.photos/id/575/480/320.webp" class="img-fluid" alt="Nulla ex nihil eligendi tempora">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/110/1200/800.webp">
          <img src="https://picsum.photos/id/110/480/320.webp" class="img-fluid" alt="Nemo perspiciatis voluptatum">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/177/1200/800.webp">
          <img src="https://picsum.photos/id/177/480/320.webp" class="img-fluid" alt="Accusantium consequuntur modi">
        </a>
      </div>
      <div class="col">
        <a class="gallery-item" href="https://picsum.photos/id/197/1200/800.webp">
          <img src="https://picsum.photos/id/197/480/320.webp" class="img-fluid" alt="Dolore asperiores reprehenderit">
        </a>
      </div>
    </div>
  </div>
</section>

<div class="modal fade lightbox-modal" id="lightbox-modal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-fullscreen">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-body">
        <div class="lightbox-content">
          <!-- JS content here -->
        </div>
      </div>
    </div>
  </div>
</div>

Customize the gallery by adding your own images and captions within the <div class="row"> element. Each gallery item should have an <a> tag with an href attribute pointing to the full-size image and an <img> tag with the image source and alt text.

3. If you want to customize the gallery’s appearance, you can add the following CSS styles to your HTML or link an external CSS file.

:root {
  --lightbox: rgb(0 0 0 / 0.75);
  --carousel-text: #fff;
}

body {
  margin: 1.5rem 0 3.5rem;
}

@keyframes zoomin {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.gallery-item {
  display: block;
}

.gallery-item img {
  box-shadow: 0 1rem 1rem rgba(0, 0, 0, 0.15);
  transition: box-shadow 0.2s;
}

.gallery-item:hover img {
  box-shadow: 0 1rem 1rem rgba(0, 0, 0, 0.35);
}

.lightbox-modal .modal-content {
  background-color: var(--lightbox);
}

.lightbox-modal .btn-close {
  position: absolute;
  top: 1.25rem;
  right: 1.25rem;
  font-size: 1.25rem;
  z-index: 10;
  filter: invert(1) grayscale(100);
}

.lightbox-modal .modal-body {
  display: flex;
  align-items: center;
  padding: 0;
}

.lightbox-modal .lightbox-content {
  width: 100%;
}

.lightbox-modal .carousel-indicators {
  margin-bottom: 0;
}

.lightbox-modal .carousel-indicators [data-bs-target] {
  background-color: var(--carousel-text) !important;
}

.lightbox-modal .carousel-inner {
  width: 75%;
}

.lightbox-modal .carousel-inner img {
  animation: zoomin 10s linear infinite;
}

.lightbox-modal .carousel-item .carousel-caption {
  right: 0;
  bottom: 0;
  left: 0;
  padding-bottom: 2rem;
  background-color: var(--lightbox);
  color: var(--carousel-text) !important;
}

.lightbox-modal .carousel-control-prev,
.lightbox-modal .carousel-control-next {
  width: auto;
}

.lightbox-modal .carousel-control-prev {
  left: 1.25rem;
}

.lightbox-modal .carousel-control-next {
  right: 1.25rem;
}

@media (min-width: 1400px) {
  .lightbox-modal .carousel-inner {
    max-width: 60%;
  }
}

[data-bs-theme = "dark"] .lightbox-modal .carousel-control-next-icon,
[data-bs-theme = "dark"] .lightbox-modal .carousel-control-prev-icon {
    filter: none;
}

4. Finally, add the following JavaScript code to your project. This code handles the lightbox functionality and ensures that clicking on an image opens it in a fullscreen lightbox.

const html = document.querySelector('html');
html.setAttribute('data-bs-theme', 'dark');

const galleryGrid = document.querySelector(".gallery-grid");
const links = galleryGrid.querySelectorAll("a");
const imgs = galleryGrid.querySelectorAll("img");
const lightboxModal = document.getElementById("lightbox-modal");
const bsModal = new bootstrap.Modal(lightboxModal);
const modalBody = lightboxModal.querySelector(".lightbox-content");

function createCaption (caption) {
  return `<div class="carousel-caption d-none d-md-block">
      <h4 class="m-0">${caption}</h4>
    </div>`;
}

function createIndicators (img) {
  let markup = "", i, len;

  const countSlides = links.length;
  const parentCol = img.closest('.col');
  const curIndex = [...parentCol.parentElement.children].indexOf(parentCol);

  for (i = 0, len = countSlides; i < len; i++) {
    markup += `
      <button type="button" data-bs-target="#lightboxCarousel"
        data-bs-slide-to="${i}"
        ${i === curIndex ? 'class="active" aria-current="true"' : ''}
        aria-label="Slide ${i + 1}">
      </button>`;
  }

  return markup;
}

function createSlides (img) {
  let markup = "";
  const currentImgSrc = img.closest('.gallery-item').getAttribute("href");

  for (const img of imgs) {
    const imgSrc = img.closest('.gallery-item').getAttribute("href");
    const imgAlt = img.getAttribute("alt");

    markup += `
      <div class="carousel-item${currentImgSrc === imgSrc ? " active" : ""}">
        <img class="d-block img-fluid w-100" src=${imgSrc} alt="${imgAlt}">
        ${imgAlt ? createCaption(imgAlt) : ""}
      </div>`;
  }

  return markup;
}

function createCarousel (img) {
  const markup = `
    <!-- Lightbox Carousel -->
    <div id="lightboxCarousel" class="carousel slide carousel-fade" data-bs-ride="true">
      <!-- Indicators/dots -->
      <div class="carousel-indicators">
        ${createIndicators(img)}
      </div>
      <!-- Wrapper for Slides -->
      <div class="carousel-inner justify-content-center mx-auto">
        ${createSlides(img)}
      </div>
      <!-- Controls/icons -->
      <button class="carousel-control-prev" type="button" data-bs-target="#lightboxCarousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#lightboxCarousel" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>
    `;

  modalBody.innerHTML = markup;
}

for (const link of links) {
  link.addEventListener("click", function (e) {
    e.preventDefault();
    const currentImg = link.querySelector("img");
    const lightboxCarousel = document.getElementById("lightboxCarousel");

    if (lightboxCarousel) {
      const parentCol = link.closest('.col');
      const index = [...parentCol.parentElement.children].indexOf(parentCol);

      const bsCarousel = new bootstrap.Carousel(lightboxCarousel);
      bsCarousel.to(index);
    } else {
      createCarousel(currentImg);
    }

    bsModal.show();
  });
}

That’s it! You’ve successfully implemented a Bootstrap 5 gallery with a lightbox feature. Customize it further to suit your project’s needs by adding more images or modifying the gallery layout and styles as required.

1 thought on “Bootstrap 5 Gallery With Lightbox”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X