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.
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">
#shadowing
{
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #CCA;
z-index:10;
opacity:0.5;
}
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 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"
onclick="document.getElementById('box').style.display='none';
document.getElementById('filter').style.display='none'">
</div>
#box
{
display: none;
position: fixed;
top: 20%;
left: 20%;
width: 60%;
height: 60%;
max-height:400px;
padding: 0;
margin:0;
border: 1px solid black;
background-color: white;
z-index:11;
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';
document.getElementById("shadowing").style.display='none'">
</span>
</div>
<div id="boxcontent"> Ceci est le contenu statique provisoire de la boite. </div>
</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.
- Download all lightbox demos. With CSS and JavaScript code.