How to create Javascript and CSS popup with Lightbox effect

This tutorial helps you to create an lightbox effect using css.


<a href="#" onclick="lightbox_open();">Open lightbox</a>
<div id="light"></div>
<div id="fade" onClick="lightbox_close();"></div>

The link with onclick attribute launches the popup window.

Fade is the background layer for the lightbox what makes the whole window dark.

Light is the container where you can place your HTML code, text, image anything you want to display.


window.document.onkeydown = function (e)
    if (!e){
        e = event;
    if (e.keyCode == 27){

Checkes if any key pressed. If ESC key pressed it calls the lightbox_close() function.

function lightbox_open(){

This script makes light and fade divs visible by setting their display properties to block. Also it scrolls  the browser to top of the page to make sure, the popup will be on middle of the screen.

function lightbox_close(){

This makes light and fade divs invisible by setting their display properties to none.

    display: none;
    position: fixed;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: #000;
    -moz-opacity: 0.7;
    filter: alpha(opacity=70);
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 200px;
    margin-left: -150px;
    margin-top: -100px;                 
    padding: 10px;
    border: 2px solid #FFF;
    background: #CCC;

To place light div to middle of the screen, make sure you set margin-left to half of width (300/2=150), and margin-top to half of height (200/2=100).

If you can not see the fade, light divs on your website, try to set a higher z-index. Don’t forget, that light div needs higher z-index than fade to put it on front.

Please follow and like us:

Leave a Comment

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