Enhancing our simple responsive image gallery

Let’s look at adding lightbox type functionality to view images larger.

Tim Wells


This follows on from my previous post on Creating a simple responsive image gallery with HTML and CSS so if you haven’t done that this won’t make much sense. If you’ve done that and would like to enhance it by adding in “lightbox” style image viewer that pops up over the top to show a larger image.

Open the code from the previous article and let’s first add a couple of extra styles to the css.

#darkbox { width:1280px; height:720px; position:absolute; top:0; left:0; background-color:#333; overflow: hidden; text-align:center;}.darkboximg { padding:5%; max-width: 1216px; max-height: 684px; }

We’ll add these into the style tag or the css file if you’ve created a css file for it. One style will be for the box that will show the image inside. I’ve set a width of 1280px and a height of 720px. You can adjust the sizes to suit your needs but the important thing is to set the max-width and max-height of the .darkboximg class to be 5% less than the size of the darkbox width and height.

Tip: you can calculate 5% less using for example: 1280-(1280*0.05)

Next we need to add some JavaScript to make things happen. You can add this inside script tags at the bottom of the page, or you can put it into a js file and reference that using script tags.

We’ll add a boolean to track if the box is open.

let darkBoxVisible = false;

Next we will add a method to display the box containing the image.

Note: I’ve called mine darkbox because I prefer the dark styling. Feel free to use lightbox and lighter coloured styling if you prefer that.

function showDarkbox(url) {
if(!darkBoxVisible) {
let x = (window.innerWidth - 1280) / 2;
let y = window.scrollY + 50;
// Create the darkBox
var div = document.createElement("div");
div.id = "darkbox";
div.innerHTML = '<img class="darkboximg" src="'+url+'" />';
let box = document.getElementById("darkbox");
box.style.left = x.toString()+"px";
box.style.top = y.toString()+"px";
box.style.height = 'auto';
box.addEventListener('click', (event) => {
// Remove it
let element =…



Tim Wells

Self taught software developer and photographer.