Responsive Modal LightBox with CSS & JS (no plugins)

Learn how to create responsive LightBox, click image to zoom with CSS and JS

HTML (Add this code at the end of body):

<div id="fancybox" class="modal" style="display: none;">
	<span class="fancybox-close">&times;</span>
	<img class="fancybox-content" id="fancybox-img">
	<div id="fancybox-caption"></div>
</div>

CSS:

/* Fancybox */
.fancyimg {
	border-radius: 5px;
	cursor: pointer;
	transition: 0.3s;
}

.fancyimg:hover {opacity: 0.7;}

/* The Modal (background) */
#fancybox {
	position: fixed; /* Stay in place */
	z-index: 1; /* Sit on top */
	padding: 20px; /* Location of the box */
	left: 0;
	top: 0;
	width: 100%; /* Full width */
	height: 100%; /* Full height */
	overflow: auto; /* Enable scroll if needed */
	background-color: rgb(0,0,0); /* Fallback color */
	background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.fancybox-content {
	margin: auto;
	display: block;
	width: 100%;
	max-width: 900px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#fancybox-caption {
	margin: auto;
	display: block;
	width: 80%;
	max-width: 700px;
	text-align: center;
	color: #ccc;
	padding: 10px 0;
	height: 40px;
}

/* Add Animation - Zoom in the Modal */
.fancybox-content, #fancybox-caption { 
	-webkit-animation-name: zoom;
	-webkit-animation-duration: 0.6s;
	animation-name: zoom;
	animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
	from {-webkit-transform:scale(0)} 
	to {-webkit-transform:scale(1)}
}

@keyframes zoom {
	from {transform:scale(0)} 
	to {transform:scale(1)}
}

/* The Close Button */
.fancybox-close {
	position: absolute;
	top: 15px;
	right: 35px;
	color: #f1f1f1;
	font-size: 40px;
	font-weight: bold;
	transition: 0.3s;
}

.fancybox-close:hover,
.fancybox-close:focus {
	color: #bbb;
	text-decoration: none;
	cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
	.fancybox-content {
		width: 100%;
	}
}
/* FancyBox end */

JS:

$("img.fancyimg").on("click", function() {
	var img_src = $(this).attr("data-big");
	var img_src = img_src ? img_src : $(this).attr("src");
	$("#fancybox").show();
	$("#fancybox-img").attr("src", img_src);
	$("#fancybox-caption").html($(this).attr("alt"));
});


$(".fancybox-close").on("click", function() {
	$("#fancybox").hide();
});

Configuration, Just one 😉

  1. Add ‘class=”fancyimg”‘ to the img tag you wanna click and zoom

P.S.: You can also show large image by setting data attribute: data-big=”/big-img-path”

That’s it, you’re good to go with LightBox built with CSS & Javascript without using any plugins. Enjoy 🙂