How to Create a Lightbox using CSS and Javascript

First of all, What is a Lightbox?

You can call it Lightbox, Greybox or Thickbox. These all mean the same thing. Basically Lightbox is an effect that fades the page in the background to show you new content in the foreground.

In this post we will learn how to open up a Lightbox on the event of a mouse click. So basically when you click certain content on a webpage, it will trigger the light box to appear in the foreground.

I had first created the lightbox effect for a website which i designed for a state level project competition. You can see it in the screenshot below. The before and after events are displayed in the screenshot below.


Before: That is how the web page looks like before clicking/triggering the lightbox code.
After: That is how the web page looks like after clicking/triggering the lightbox code.

There are tons of Lightbox codes available over the Internet with great features as well as limitations. Most of them require heavy use of javascript, while some may require additional frameworks to be installed.

But the code which i am sharing in this post is the simplest version and easy to understand. So lets begin,

First lets discuss about the CSS Code

The dark_overlay class is the layer that will add a slightly transparent overlay on the current webpage. It’s going to apply a black 80% opaque background over the current web page after the lightbox is triggered. (look at the z-index).

The white content class is the layer which will create a box in the foreground over the transparent overlay, which is called the lightbox. It’s a white layer to be placed over the black_overlay layer (look at the z-index, greater than the black_overlay one). Also the overflow allows you to have a scrollable content even after the lightbox is triggered.

1) Now add the following code inside the body tags of your HTML Document:

2) Once you do that you will need to add a trigger (an event which will open lightbox). For example, a trigger can be On Mouse Click, or On Page Load.

So add this code just below the opening body tag ( <body> ) :

3) Remember to include the code to close the Lightbox, for example:

Replace the division of id = light, which was used in the part 1) code with the following code:

Combining all parts of code, We get :

You can find the Live Demo of this CSS Lightbox by Clicking over Here

This is a very basic lightbox. And i hope this might be useful for those who are developing their own lightbox for the very first time.

Also i will try and customize the looks of this lightbox in the next post.  So keep checking this post, Since i will be adding the links to the customized css lightbox over here.

Leave a Reply

Your email address will not be published. Required fields are marked *