How to create a lightbox with Bootstrap?

How to create a lightbox with Bootstrap?


This article shows you how to create a lightbox with bootstrap

The modal lightbox is a box centered with a dark background and with an image as content. It is not shown at first (or not present in the DOM at first). The user needs to click on a link to open it up.

Steps by step

Add the bootstrap resources to your page

<link href="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Add the HTML

The lightbox is hidden until the user clicks on the image.

<div class="modal" id="lightBoxModalId" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: fit-content;">
		<div class="modal-content">
			<div class="modal-body" style="padding: 0">
				<button type="button" class="close-media" data-bs-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				<img src="/_media/web/css/surfer-in-the-see-200h.png">

Style it as you want: Close button in the top right

A little bit of css to locate the close button in the top right corner of the lightbox.

.close-media {
	background-color: transparent;
	border: 0;
	font-size: 1.5rem;
	font-weight: 700;
	line-height: 1;
	color: #000;
	text-shadow: 0 1px 0 #fff;
	opacity: .5;
	position: absolute;
	right: 2px;
	top: 2px;

Add the original image

The image shown is small (200px) and is wrapped in a link that will open the lightbox when clicked

<a class="lightbox" href="/_media/web/css/surfer-in-the-see-200h.png">
    <img src="/_media/web/css/surfer-in-the-see-200h.png" width="200"/>

Add the code to open the lightbox on click

The javascript will show the lightbox when clicking on the image link.

document.querySelectorAll(".lightbox").forEach((lightBoxAnchor) => {
    lightBoxAnchor.addEventListener("click", async function (event) {
      let lightBoxElement = document.getElementById('lightBoxModalId');
      let lightBoxModal = bootstrap.Modal.getOrCreateInstance(lightBoxElement);


Click on the image to see the lightbox.

Discover More
Card Puncher Data Processing
UI - Overlay

An overlay component is a component that comes above the actual components in a absolute position. In Html, it would have a higher value on the z scale (ie z-index) When two elements overlay each other,...
Card Puncher Data Processing
What is a LightBox ?

A Lightbox displays images and videos by filling the screen and dimming out the rest of the web page. It's a central overlay (modal) that adds a dark background to give more contrast (ie more light) ...

Share this page:
Follow us:
Task Runner