Create a Lightbox effect only with CSS – no javascript needed

Create a Lightbox effect only with CSS – no javascript needed

//
//

You may call it Lightbox, or Greybox, or Thickbox, but it’s always the same effect.

When you are on a page, and click on a photo or trig some event, a Lightbox is an effect that fades the pagein the background to show you new content in the foreground.

I mean this effect

Lightbox

In the upper example, when clicking on a photo the site fades to black and shows the photo, in the lower one when clicking on “login” the site fades to white and shows the login form.

There are tons of Lightbox scripts in the web, each one with its unique features and limitations, but all require massive use of Javascript or the installation of javascript frameworks.

In some cases, there are “lightweight” versions with “only” 40KB of Javascript.

This example does not want to compete with those scripts, but if you are looking for a simple, 100% CSS, 0% javascript lightbox, this may help you.

Features of this Lightbox:

100% CSS as said
You can insert any content in it (some scripts out there only allow images)

That’s all. Did you need something more? Think wisely…

Let’s start with the CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
.black_overlay{
	display: none;
	position: absolute;
	top: 0%;
	left: 0%;
	width: 100%;
	height: 100%;
	background-color: black;
	z-index:1001;
	-moz-opacity: 0.8;
	opacity:.80;
	filter: alpha(opacity=80);
}

.white_content {
	display: none;
	position: absolute;
	top: 25%;
	left: 25%;
	width: 50%;
	height: 50%;
	padding: 16px;
	border: 16px solid orange;
	background-color: white;
	z-index:1002;
	overflow: auto;
}

The black_overlay class is the layer that will make the web page seem to fade. It’s a black 80% opaque background as long and wide as the browser that will overlay the web page (look at the z-index) and at the moment is not shown (look at the display).

The white content class is the layer with the photo/login screen/whatever you want to appear in the Lightbox overlay. It’s a white layer to be placed over the black_overlay layer (look at the z-index, greater than the black_overlay one). The overflow allows you to have a scrollable content.

In the html file, put this line just before the tag

1
<div id="light">Hi, I am an happy lightbox</div><div id="fade"></div>

Now, trig the action you want to open the Lightbox and insert this code:

1
document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block';

For example, in a link would be:

1
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Click me</a>

Remember to include in the lightbox the code to close it, for example

1
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Hide me</a>

A complete example page could be

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>LIGHTBOX EXAMPLE</title>
		<style>
		.black_overlay{
			display: none;
			position: absolute;
			top: 0%;
			left: 0%;
			width: 100%;
			height: 100%;
			background-color: black;
			z-index:1001;
			-moz-opacity: 0.8;
			opacity:.80;
			filter: alpha(opacity=80);
		}
		.white_content {
			display: none;
			position: absolute;
			top: 25%;
			left: 25%;
			width: 50%;
			height: 50%;
			padding: 16px;
			border: 16px solid orange;
			background-color: white;
			z-index:1002;
			overflow: auto;
		}
	</style>
	</head>
	<body>
		<p>This is the main content. To display a lightbox click <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a></p>
		<div id="light">This is the lightbox content. <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a></div>
		<div id="fade"></div>
	</body>
</html>

That you can find up and running in this page.

In this example everything is static and preloaded, but you can easily add some php/ajax code to make it more dynamic while keeping the effect 100% CSS based.

Hope you will find it useful, should you use it in one of your works send me a comment and I’ll feature your site as example.

source: emanueleferonato.com

css/ Javascript: Form in a Lightbox

Form in a Lightbox

Showing a form in the lightbox, with fading effect in option, should encourage visitors to fill it…

We have seen how to create a lightbox with fade in effect, we use the same JavaScript code but we also simplify the CSS code because a form has a submit button and a cancel button, so the close button may be removed.

The form is placed directly in the box on the page and does not need to be loaded dynamically, although that option remains possible, and it is also possible to create several boxes and leave a choice to the user. We can adapt the code to do so.

Demonstration

Our example uses a form composed of objects of different types:
– A text field.
– Two alternative radio buttons.
– A selection list.

In our example, data entered and choices made by users are sent to another web page. These data are collected by a JavaScript code placed in this other page:

function retrieve()
{

	var parameters = location.search.substring(1).split("&");
	var temp = parameters[0].split("=");
	mail = unescape(temp[1]);

	temp = parameters[1].split("=");
	sex = unescape(temp[1]);

	temp = parameters[2].split("=");
	city = unescape(temp[1]);

	var data =  document.getElementById("data");

	data.innerHTML = "Email: " + mail + "<brr";
	data.innerHTML += "Genre: " + sex + "<br>";
	data.innerHTML += "City: " + city + "<br>";

}

retrieve();

About the code in the page of the form, it is the same as the code previously used, except that the dynamic filling part is removed. This gives a simplified openbox function.

function openbox(formtitle, fadin)
{
  var box = document.getElementById('box'); 
  document.getElementById('filter').style.display='block';

  var btitle = document.getElementById('boxtitle');
  btitle.innerHTML = formtitle;

  if(fadin)
  {
	 gradient("box", 0);
	 fadein("box");
  }
  else
  { 	
    box.style.display='block';
  }  	
}

We can see that the function as a parameter for the title of the form, and the fadin option, its value is 1 if you ask a fade, and 0 if the display must be immediate.

The function closebox is now associated to the “cancel” button:

<input type="button" name="cancel" value="Cancel" onclick="closebox()">

The CSS is the same with the deletion of some descriptors. Indeed, the code to insert a box in a page is simpler:

<div id="filter"></div>
<div id="box"></box>
    <span id="boxtitle"></span>
    <form method="GET" action="lightbox-form-test.html" >
        ... objects of the form...
    </form>
</div>
</div>

source: xul.fr

css:Sliding Doors of CSS

A rarely discussed advantage of CSS is the ability to layer background images, allowing them to slide over each other to create certain effects. CSS2’s current state requires a separate HTML element for each background image. In many cases, typical markup for common interface components has already provided several elements for our use.

One of those cases is tabbed navigation. It’s time to take back control over the tabs which are continually growing in popularity as a primary means of site navigation. Now that CSS is widely supported, we can crank up the quality and appearance of the tabs on our sites. You’re most likely aware that CSS can be used to tame a plain unordered list. Maybe you’ve even seen lists styled as tabs, looking something like this:

[Ordinary example of CSS-based tabs, using flat colors and squared-off corners.]

What if we could take the exact same markup from the tabs above, and turn them into something like this:

[Stylized tabs using rounded corners and subtle three-dimensional shading.]

With simple styling, we can.

Where’s the Innovation?

Many of the CSS-based tabs I’ve seen suffer from the same generic features: blocky rectangles of color, maybe an outline, a border disappears for the current tab, a color changes for the hover state. Is this all CSS can offer us? A bunch of boxes and flat colors?

Prior to a more widespread adoption of CSS, we started seeing a lot of innovation in navigation design. Creative shapes, masterful color blending, and mimicry of physical interfaces from the real world. But these designs often relied heavily on a complex construction of text-embedded images, or were wrapped with multiple nested tables. Editing text or changing tab order involved a cumbersome process. Text resizing was impossible, or caused significant problems with page layout.

Pure text navigation is much easier to maintain and loads more quickly than text-as-image navigation. Also, even though we can add alt attributes to each image, pure text is even more accessible since it can be resized by users with impaired vision. It’s no wonder that pure text-based navigation, styled with CSS, is leaping back into web design. But most CSS-based tab design so far is a step back in appearance from what we used to do — certainly nothing to be included in a design portfolio. A newly adopted technology (like CSS) should allow us to create something better, without losing the design quality of previous table hacks and all-image-based tabs.

The Sliding Doors Technique

Beautifully crafted, truly flexible interface components which expand and contract with the size of the text can be created if we use two separate background images. One for the left, one for the right. Think of these two images as Sliding Doors that complete one doorway. The doors slide together and overlap more to fill a narrow space, or slide apart and overlap less to fill a wider space, as the diagram below shows:

[Diagram shows two sets of doors. The first set is pushed together to take up less space. The second set is spaced apart to occupy a wider space.]

With this model, one image covers up a portion of the other. Assuming we have something unique on the outside of each image, like the rounded-corner of a tab, we don’t want the image in front to completely obscure the image behind it. To prevent this from happening, we make the image in front (left-side for this example) as narrow as possible. But we keep it just wide enough to reveal that side’s uniqueness. If the outside corners are rounded, we should make the front image only as wide as the curved portion of the image:

[Diagram shows an isolated narrow left-side image with rounded top-left corner, then repeats that same image placed in front of a right-side image with a rounded right-side corner.]

If the object grows any larger than the width shown above, due to differing text or type size changes, the images will get pulled apart, creating an ugly gap. We need to make an arbitrary judgment about the amount of expansion we’ll accommodate. How large do we think the object might grow as text is resized in the browser? Realistically, we should account for the possibility of our tab text increasing by at least 300%. We need to expand the background images to compensate for that growth. For these examples we’ll make the back image (right-side) 400×150 pixels, and the front image 9×150 pixels.

Keep in mind that background images only show in the available “doorway” of the element to which they’re applied (content area + padding). The two images are anchored to the outside corners of their respective elements. The visible portions of these background images fit together inside the doorway to form a tab-like shape:

[Diagram shows both images with extra height added to the bottom. The right-side image also has extra width added to the left. The only portions which remain visible fit together perfectly to form the illustion of a tab-like shape.]

If the tab is forced to a larger size, the images slide apart, filling a wider doorway, revealing more of each image:

[Diagram shows the two images pulled apart slightly to create a wider tab, as well as a slightly taller vertical height to reveal more of each image. Since both background images have allowances for expansion, the the illusion is that the tab itself expanded naturally with the text contained inside.]

For this example, I used Photoshop to create two smooth, slightly three-dimensional, custom tab images shown at the beginning of this article. For one of the tabs, the fill was lightened and the border darkened — the lighter version will be used to represent the “current” tab. Given this technique’s model for left and right tab images, we need to expand coverage area of the tab image, and cut it into two pieces:

[Left- and right-side images]

The same thing needs to happen with the lighter current tab image. Once we have all four images created, (1, 2, 3, 4) we can jump into the markup and CSS for our tabs.

Tab Creation

As you explore the creation of horizontal lists with CSS, you’ll notice at least two methods for arranging a group of items into one row. Each comes with its own benefits and drawbacks. Both require dealing with rather funky aspects of CSS which quickly become confusing. One uses the inline box, the other uses floats.

The First Method — and possibly the more common — is to change the display of each list item to “inline”. The inline method is attractive for its simplicity. However, the inline method causes a few rendering problems in certain browsers for the Sliding Doors technique we’re going to discuss. The Second Method, which is the one we’ll focus on, uses floats to place each list item in a horizontal row. Floats can be equally frustrating. Their seemingly inconsistent behavior circumvents all natural logic. Still, a basic understanding of how to deal with multiple floated elements, and the means to reliably “break out” of floats (or contain them) can achieve wonders.

We’re going to nest several floated elements within another containing floated element. We do this so that the outer parent float completely wraps around the floats inside. This way, we’re able to add a background color and/or image behind our tabs. It’s important to remember that the next element following our tabs needs to reset its own position by using the CSS clear property. This prevents the floated tabs from affecting the position of other page elements.

Let’s begin with the following markup:

  <div id="header">
    <ul>
      <li><a href="#">Home</a></li>
      <li id="current"><a href="#">News</a></li>
      <li><a href="#">Products</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </div>

In reality, the #header div might also contain a logo and a search box. For our example, we’ll shorten the href value in each anchor. Obviously, these values would normally contain file or directory locations.

We begin styling our list by floating the #header container. This helps ensure the container actually “contains” the list items inside which will also be floated. Since the element is floated, we also need to assign it a width of 100%. A temporary yellow background is added to ensure this parent stretches to fill the entire area behind the tabs. We also set some default text properties, ensuring everything inside will be the same:

  #header {
    float:left;
    width:100%;
    background:yellow;
    font-size:93%;
    line-height:normal;
    }

For now, we also set all of the default margin/padding values of the unordered list and list items to “0”, and remove the list item marker. Each list item gets floated to the left:

  #header ul {
    margin:0;
    padding:0;
    list-style:none;
    }
  #header li {
    float:left;
    margin:0;
    padding:0;
    }

We set the anchors to block-level elements so we can control all aspects without worrying about the inline box:

  #header a {
    display:block;
    }

Next, we add our right-side background image to the list item (changes/additions are bolded):

  #header li {
    float:left;
    background:url("norm_right.gif")
      no-repeat right top;
    margin:0;
    padding:0;
    }

Before adding the left-side image, we pause so we can see what we have so far in Example 1. (In the example file, ignore the rule I’ve applied to the body. It only sets up basic values for margin, padding, colors, and text.)

– – –

Now we can place the left-side image in front of the right by applying it to the anchor (our inner element). We add padding at the same time, expanding the tab and pushing the text away from the tab edges:

  #header a {
    display:block;
    background:url("norm_left.gif")
      no-repeat left top;
    padding:5px 15px;
    }

This gives us Example 2. Note how our tabs have begun to take shape. At this point, a word of acknowledgement to confused IE5/Mac users, who are wondering, “What’s going on here? The tabs are stacked vertically and stretch across the entire screen.” Don’t worry, we’ll get to you soon. For now, do your best to follow along, or temporarily switch to another browser if one is handy, and be assured we’ll fix the IE5/Mac issue shortly.

– – –

Now that we have the background images in place for normal tabs, we need to change the images used for the “current” tab. We do this by targeting the list item which contains id="current" and the anchor inside it. Since we don’t need to alter any other aspects of the background, other than the image, we use the background-image property:

  #header #current {
    background-image:url("norm_right_on.gif");
    }
  #header #current a {
    background-image:url("norm_left_on.gif");
    }

We need some kind of border along the bottom of our tabs. But applying a border property to the parent #header container won’t allow us to “bleed” the current tab through this border. Instead, we create a new image with the border we want included along the bottom of the image. While we’re at it, we also add a subtle gradient so it looks like this:

We apply that image to the background of our #header container (instead of the yellow color we had), push the background image to the bottom of the element, and use a background color matching the top of this new image. At the same time, we remove the padding from the body element I originally inserted for us, and apply 10 pixels of padding to the top, left, and right sides of the ul:

  #header {
    float:left;
    width:100%;
    background:#DAE0D2 url("bg.gif")
      repeat-x bottom;
    font-size:93%;
    line-height:normal;
    }
  #header ul {
    margin:0;
    padding:10px 10px 0;
    list-style:none;
    }

To complete the tab effect, we need to bleed the current tab through the border, as mentioned above. You might think we would apply bottom borders to our tabs matching the border color in the #header background image we just added, then change the border color to white for the current tab. However, doing this would result in a tiny “step” visible to pixel-precision eyes. Instead, if we alter the padding of the anchors, we can create perfectly squared-off corners inside the current tab, as the magnified example below shows:

[Enlargement of two tab versions, the first showing the tiny 1-pixel step from using the bottom border, the second showing a perfect 90-degree angle.]

We do this by decreasing the bottom padding of the normal anchor by 1 pixel (5px – 1px = 4px), then adding that pixel back to the current anchor:

  #header a {
    display:block;
    background:url("norm_left.gif")
      no-repeat left top;
    padding:5px 15px 4px;
    }
  #header #current a {
    background-image:url("norm_left_on.gif");
    padding-bottom:5px;
    }

The change allows the bottom border to show through for normal tabs, but hides it for the current tab. This brings our code up to Example 3.

Finishing Touches

Keen eyes may have noticed white tab corners showing up in the previous example. These opaque corners are currently preventing the image in the back from showing through the left corner of the image in front. In theory, we could attempt to match the corners of the tab images with a portion of the background behind them. But our tabs can grow in height, which pushes the background behind them lower, shifting the background color we tried to match. Instead, we change the images, making the corners of our tabs transparent. If the curves are anti-aliased, we matte the edges to an average of the background color behind them.

Now that the corners are transparent, a piece of the right-side image shows through the corner of the left-side image. To compensate for this, we add a small amount of left padding to the list item equivalent to the width of the left-side image (9px). Since padding was added to the list item, we need to remove that same amount from the anchor to keep the text centered (15px – 9px = 6px):

  #header li {
    float:left;
    background:url("right.gif")
      no-repeat right top;
    margin:0;
    padding:0 0 0 9px;
    }
  #header a {
    display:block;
    background:url("left.gif")
      no-repeat left top;
    padding:5px 15px 4px 6px;
    }

However, we can’t leave it at that either, because our left-side image now gets pushed away from the left tab edge by the 9 pixels of padding we just added. Now that the inner edges of the left and right visible doorways butt up against each other, we no longer need to keep the left image in the front. So we can switch the order of the two background images, applying them to opposite elements. We also need to swap the images used for the current tab:

  #header li {
    float:left;
    background:url("left.gif")
      no-repeat left top;
    margin:0;
    padding:0 0 0 9px;
    }
  #header a, #header strong, #header span {
    display:block;
    background:url("right.gif")
      no-repeat right top;
    padding:5px 15px 4px 6px;
    }
  #header #current {
    background-image:url("left_on.gif");
    }
  #header #current a {
    background-image:url("right_on.gif");
    padding-bottom:5px;
    }

Once we do this, we arrive at Example 4. Note that the tweaks required to make the corners transparent creates a small dead space on the left side of the tab where it’s not clickable. The dead space is outside the text area, but it is slightly noticeable. Using transparent images for each side of our tabs is not required. If we prefer not to have the small dead space, we need to use a flat color behind the tabs, then use this color in the corner of our tab images instead of making them transparent. We’ll keep the new transparent corners for now.

– – –

For the remaining tweaks, we make a slew of changes all at once: bold all tab text, change normal tab text to a brown color, make current tab text a dark gray color, remove link underlines, and change the text color for the link hover state to the same dark gray. We see all additions and changes so far represented in Example 5.

One Hack for Consistency

After Example 2, we acknowledged a problem with IE5/Mac where each tab stretched across the entire browser width, forcing each one to stack vertically on top of each other. Not quite the effect we were intending.

In most browsers, floating an element will act sort of like shrink-wrapping it — it gets shrunk to the smallest possible size of the contents it contains. If a floated element contains (or is) an image, the float will shrink to the width of the image. If it contains only text, the float will shrink to the width of the longest non-wrapping line of text.

A problem enters the picture for IE5/Mac when an auto-width block-level element is inserted into a floated element. Other browsers still shrink the float as small as possible, regardless of the block-level element it contains. But IE5/Mac doesn’t shrink the float in this circumstance. Instead, it expands the float and block-level element to full available width. To work around this problem, we need to float the anchor also, but only for IE5/Mac, lest we throw off other browsers. First we’ll set the existing rule to float the anchor. Then we’ll use the Commented Backslash Hack to hide a new rule from IE5/Mac which removes the float for all other browsers:

  #header a {
    float:left;
    display:block;
    background:url("right.gif")
      no-repeat right top;
    padding:5px 15px 4px 6px;
    text-decoration:none;
    font-weight:bold;
    color:#765;
    }
  /* Commented Backslash Hack
     hides rule from IE5-Mac \*/
  #header a {float:none;}
  /* End IE5-Mac hack */

IE5/Mac browsers should now display the tabs as intended, according to Example 6. Nothing should have changed for non-IE5/Mac browsers. Note that IE5.0/Mac suffers from a lot of rendering bugs that were fixed in the upgrade to IE5.1. Because of this, the Sliding Doors technique suffers in version 5.0 beyond a point I’m willing to hack. Since the upgrade to IE5.1/Mac has been readily available for some time now, the percentage of OS 9 Macs still running IE5.0 should be tapering off to almost nothing.

Variations

We just walked through the Sliding Doors technique for creating tabbed navigation with pure text, marked up with an unordered list of links, altered with a few custom styles. It loads fast, is simple to maintain, and text within can be scaled up or down significantly in size without breaking the design. Need we mention how flexible the technique can be for creating any type of sophisticated-looking navigation?

Use of this technique is only limited by our imagination. Our final example represents just one possibility. But we shouldn’t let an example place boundaries on our ideas.

For instance, tabs aren’t required to be symmetrical. I quickly created Version 2 of these tabs, which avoids the shaded 3-D look in favor of flat colors, angular edges, and a wider and more detailed left-side. We can even switch the order of left/right images, depending on the design, as Version 2 shows. With some careful planning and clever image manipulation, the bottom border could be abandoned in favor of matching the tab images with the background running behind them, as shown in my Deco-inspired Version 3. If your browser supports alternate style sheet switching, you can even view this master file, and switch between the three different versions by alternating between style sheets.

Other effects we don’t cover here could be added on top of this technique. In the example I ran through, I changed the text color for the hover state, but entire images could be swapped out to create interesting rollover effects. Wherever two nested HTML elements already exist in the markup, CSS can be used to layer background images for effects we haven’t even begun to imagine yet. We created a horizontal row of tabs in this example, but Sliding Doors could be used in a many other situations. What can you do with it?

source: Douglas Bowman