Looking to create a responsive image lightbox? After starting from an example on W3Schools (https://www.w3schools.com/howto/howto_js_lightbox.asp), I ran into issues with portrait oriented images. Ideally, the solution should handle both landscape (e.g., 1200x800) and portrait (e.g., 800x1200) images.
The goal is to ensure that the images resize appropriately for different orientations and work seamlessly across modern browsers, iOS, Android, and even IE11 compatibility.
I attempted to address this by adding "max-width: 1200px;" to the lightbox-content class. While it worked for horizontal images, vertical images ended up exceeding the desired height due to enlargement.
<div class="lightbox">
<span class="close" onclick="closeLightbox()">×</span>
<div class="lightboxTitle">My Title</div>
<div class="lightbox-content">
<div class="slide"><img src="img1.jpg"></div>
<div class="slide"><img src="img2.jpg"></div>
<div class="slide"><img src="img2.jpg"></div>
<!-- Next/previous controls -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
</div>
/* The Modal (background) */
.lightbox {
display: none;
position: fixed;
z-index: 99999999;
padding-top: 60px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
}
/* Modal Content */
.lightbox-content {
position: relative;
margin: auto;
padding: 0;
width: 100%;
max-width: 1200px;
}
.lightboxTitle {
position: absolute;
top: 20px;
left: 25px;
font-size: 20px;
}
/* The Close Button */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #FF8511;
text-decoration: none;
cursor: pointer;
}
/* Hide the slides by default */
.slide {
display: none;
}
.slide img {
width: 100%;
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev {
left: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
color: #FF8511;
}