Lightbox in CSS and JavaScript

To add a lightbox to your page, you do not need for including a big Ajax framework, some lines of CSS and JavaScript are enough.

A lightbox is a windows that displays a content, either static or dynamic, while the background is darkened. This is the source of the effect: the box is so enlighted.

We will create easily this effect with two <div>. The first one is a filter that covers the whole page with a reduced opacity. The second is a container for the box.

A simple demo with a static content

To display the box, click on this link.

Title of the content (image, form or other)
And this is the static content of the box.

Dynamic content in the next demo...

Creating a filter to darken the background

The filter is a <div> tag positioned by CSS over the page.

<div id="shadowing">
  display: none;
  position: fixed;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 100%;
  background-color: #CCA;
  filter: alpha(opacity=50);

The display: none property makes that the filter is not displayed initially while this is changed to display: block when we want it to appear.
The z-index property will put the filter above other elements of the page.
The opacity of 0.5 creates a semi-transparent filter, the value can vary from 0 (transparency) to 1 (opaque).
The filter: alpha(opacity=50) line is for Internet Explorer 7 only.
The color #CCA line gives the tint of old paper to the filter. You choose the hue.

Creating the light box

To achieve a box, we do use a second <div>, which according to the same principle, is not initially displayed, and appear when the user clicks on the object to display.

<div id="box" 
  display: none;
  position: fixed;
  top: 20%;
  left: 20%;
  width: 60%;
  height: 60%;
  padding: 0;
  border: 1px solid black;
  background-color: white;
  overflow: auto;

The onclick DOM method triggers two events.
- the filter ist selected on its filter ID and its display is triggered.
- the box ist selected on its firstbox ID and its display is triggered simultaneously.
z-index here is just one level above that of the filter.
oveflow:auto let scrollbars to appear when the inserted content is bigger than the box.

Adding a button to close the box

There are now embedded <div> in the box:

<div id="box">
<div id="boxheader">
      <span id="boxtitle"> Titre pour le contenu (image, formulaire ou autre)</span>
       <span id="boxclose" onclick="document.getElementById('box').style.display='none';
<div  id="boxcontent"> Ceci est le contenu statique provisoire  de la boite.  </div>

We have structured the box to give it a title bar (header), display a close button (boxclose), and an area for the content (boxcontent).
In the content area, you can place a static content, as seen in the first demo.

© 2008-2014