Beautiful Photo Stack Gallery with jQuery and CSS3 | Codrops


View demoDownload source

In this tutorial we are going to create a nice and fresh image gallery. The idea is to show the albums as a slider, and when an album is chosen, we show the images of that album as a beautiful photo stack. In the photo stack view, we can browse through the images by putting the top most image behind all the stack with a slick animation.

We will use jQuery and CSS3 properties for the rotated image effect. We will also use the webkit-box-reflect property in order to mirror the boxes in the album view – check out the demo in Google Chrome or Apple Safari to see this wonderful effect.

We will also use a bit of PHP for getting the images from each album.

So, let’s start!

The Markup

In our HTML structure we will have several elements. The main ones are for the album columns with thumbnail and description, and the preview with the photo stack.
The structure for the album view is going to look as follows:

01 <div id="ps_slider" class="ps_slider">
02
03 <a class="prev disabled"></a>
04 <a class="next disabled"></a>
05
06 <div id="ps_albums">
07
08 <div class="ps_album" style="opacity:0;">
09 <img src="albums/album1/thumb/thumb.jpg" alt=""/>
10 <div class="ps_desc">
11 <h2>Album title</h2>
12 <span>Description text</span>
13 </div>
14 </div>
15
16 <div class="ps_album" style="opacity:0;">
17 ...
18 </div>
19
20 ...
21 </div>
22
23 </div>

The opacity of the album div is going to be 0 in the beginning, we will then use JavaScript to fade in the columns.
The information that we need to provide in the HTML is the location of each album and its thumbnail images. With our little PHP script we will then get all the images from the respective album.

The structure for the dark overlay and the preview with the photo stack is going to look like this:

1 <div id="ps_overlay" class="ps_overlay" style="display:none;"></div>
2
3 <a id="ps_close" class="ps_close" style="display:none;"></a>
4
5 <div id="ps_container" class="ps_container" style="display:none;">
6 <a id="ps_next_photo" class="ps_next_photo" style="display:none;"></a>
7 </div>

We will dynamically insert the pictures of each album into the ps_container div.
Now, let’s take a look at the PHP.

The PHP

Our PHP file will be called from our JavaScript and we will get the information with AJAX call. The PHP looks as follows:

1 $location = 'albums';
2 $album_name = $_GET['album_name'];
3 $files = glob($location . '/' . $album_name . '/*.{jpg,gif,png}', GLOB_BRACE);
4 $encoded = json_encode($files);
5 echo $encoded;
6 unset($encoded);

The CSS

The style for the gallery is going to contain some CSS3 properties and also a Webkit specific property for a mirror effect.
Let’s start by resetting some paddings and margins and defining the general style for the body:

01 body, ul, li, h1, h2, h3{
02 margin:0;
03 padding:0;
04 }
05 body{
06 background:#121212;
07 font-family:Arial, Helvetica, sans-serif;
08 font-size:11px;
09 color:#fff;
10 overflow-x:hidden;
11 }

We will continue with the style of the preview. The overlay is going to have the following style:

01 .ps_overlay{
02 z-index:90;
03 background:#111;
04 width:100%;
05 height:100%;
06 position:fixed;
07 top:0px;
08 left:0px;
09 opacity:0.5;
10 }

The container for the photo stack will have a defined height and width. We will position it absolutely and center it with the “50%/negative margins” method:

01 .ps_container{
02 width:480px;
03 height:350px;
04 position:absolute;
05 top:50%;
06 margin-top:-175px;
07 left:50%;
08 margin-left:-240px;
09 z-index:100;
10 }

The image will have a thick white border and a nice box shadow. We will center the image relatively to its container but since we will only know the width and height of the images once we dynamically add them, we will set the margins in our JavaScript function:

1 .ps_container img{
2 border:10px solid #fff;
3 position:absolute;
4 top:50%;
5 left:50%;
6 -moz-box-shadow:1px 1px 10px #000;
7 -webkit-box-shadow:1px 1px 10px #000;
8 box-shadow:1px 1px 10px #000;
9 }

The close button for the preview is going to be fixed at the top right of the window:

01 a.ps_close{
02 background:#000 url(../images/close.png) no-repeat center center;
03 cursor:pointer;
04 width:56px;
05 height:56px;
06 position:fixed;
07 right:10px;
08 top:10px;
09 z-index:1000;
10 -moz-border-radius:10px;
11 -webkit-border-radius:10px;
12 border-radius:10px;
13 opacity:0.6;
14 }

We will show a “next photo” element on top of the current image when the user hovers over it:

01 a.ps_next_photo{
02 position:absolute;
03 top:50%;
04 left:50%;
05 width:56px;
06 height:56px;
07 margin:-28px 0 0 -28px;
08 z-index:200;
09 cursor:pointer;
10 background:#000 url(../images/next_photo.png) no-repeat 50% 50%;
11 opacity:0.6;
12 -moz-border-radius:10px;
13 -webkit-border-radius:10px;
14 border-radius:10px;
15 }

The hover classes for the last two elements:

1 a.ps_next_photo:hover,
2 a.ps_close:hover{
3 opacity:0.8;
4 }

Now we are going to define the style for the album view and its columns. The slider container will be positioned relatively. With the auto values for the left and right margins we center the container horizontally on the page:

1 .ps_slider{
2 width:845px;
3 height:300px;
4 position:relative;
5 margin:110px auto 0px auto;
6 }

The navigation elements are going to have the following style:

01 .ps_slider a.next,
02 .ps_slider a.prev{
03 position:absolute;
04 background-color:#000;
05 background-position:center center;
06 background-repeat:no-repeat;
07 border:1px solid #232323;
08 width:20px;
09 height:20px;
10 top:50%;
11 margin-top:-10px;
12 opacity:0.6;
13 -moz-border-radius:5px;
14 -webkit-border-radius:5px;
15 border-radius:5px;
16 cursor:pointer;
17 outline:none;
18 }
19 .ps_slider a.prev{
20 left:-30px;
21 background-image:url(../images/prev.png);
22 }
23 .ps_slider a.next{
24 right:-30px;
25 background-image:url(../images/next.png);
26 }
27 .ps_slider a.prev:hover,
28 .ps_slider a.next:hover{
29 border:1px solid #333;
30 opacity:0.9;
31 }

We also define a class for the navigation elements when they are disabled:

1 .ps_slider a.disabled,
2 .ps_slider a.disabled:hover{
3 opacity:0.4;
4 border:1px solid #111;
5 cursor:default;
6 }

Each album column is going to have the following style:

01 .ps_slider .ps_album{
02 width:140px;
03 height:310px;
04 padding:10px;
05 background-color:#333;
06 border:1px solid #444;
07 position:absolute;
08 top:0px;
09 text-align:center;
10 cursor:pointer;
11 -moz-box-shadow:1px 1px 4px #000;
12 -webkit-box-shadow:1px 1px 4px #000;
13 box-shadow:1px 1px 4px #000;
14 -webkit-box-reflect:
15 below 5px
16 -webkit-gradient(
17 linear,
18 left top,
19 left bottom,
20 from(transparent),
21 color-stop(0.6, transparent),
22 to(rgb(18, 18, 18))
23 );
24 }

The last property is the Webkit box reflex that mirrors the columns. We say that it should mirror the element in a gradient like way.

We add a hover class for the whole column:

1 .ps_slider .ps_album:hover{
2 background-color:#383838;
3 }

The thumbnail image and the content of the column are going to have the following styles:

01 .ps_slider .ps_album img{
02 height:90px;
03 border:1px solid #444;
04 -moz-box-shadow:1px 1px 4px #000;
05 -webkit-box-shadow:1px 1px 4px #000;
06 box-shadow:1px 1px 4px #000;
07 }
08 .ps_slider .ps_album .ps_desc{
09 display:block;
10 color:#666;
11 background:#111 url(../images/overlay.png) no-repeat bottom right;
12 height:200px;
13 margin-top:10px;
14 text-align:left;
15 line-height:20px;
16 overflow:hidden;
17 text-overflow:ellipsis;
18 border:1px solid #393939;
19 -moz-box-shadow:0px 0px 2px #000 inset;
20 -webkit-box-shadow:0px 0px 2px #000 inset;
21 box-shadow:0px 0px 2px #000 inset;
22 }
23 .ps_slider .ps_album:hover .ps_desc{
24 background-image:none;
25 }
26 .ps_slider .ps_album .ps_desc span{
27 display:block;
28 margin:0px 10px 10px 10px;
29 border-top:1px solid #333;
30 padding-top:5px;
31 }
32 .ps_slider .ps_album .ps_desc h2{
33 margin:10px 10px 0px 10px;
34 text-align:left;
35 padding-bottom:5px;
36 font-weight:normal;
37 color:#ddd;
38 text-shadow:0px 0px 1px #fff;
39 border-bottom:1px solid #000;
40 }

The loading element will show when we click on an album and all the images get loaded in the preview:

1 .ps_slider .loading{
2 background:#121212 url(../images/loading.gif) no-repeat 50% 50%;
3 position:absolute;
4 top:0px;
5 left:0px;
6 width:100%;
7 height:100%;
8 opacity:0.7;
9 }

For the opacity to work in IE you need to add this filter (with the right value):

filter:progid:DXImageTransform.Microsoft.Alpha(opacity=60);

I did not want to uglify the code.

Let’s add the magic!

The JavaScript

First, we need to define some variables that help us control the album navigation and keep some elements. The variable positions saves the left value for each album column. This depends on the width of the column.

01 /**
02 * navR,navL are flags for controlling the albums navigation
03 * first gives us the position of the album on the left
04 * positions are the left positions for each of the 5 albums displayed at a time
05 */
06 var navR,navL   = false;
07 var first       = 1;
08 var positions   = {
09 '0' : 0,
10 '1' : 170,
11 '2' : 340,
12 '3' : 510,
13 '4' : 680
14 }
15 var $ps_albums      = $('#ps_albums');
16 /**
17 * number of albums available
18 */
19 var elems           = $ps_albums.children().length;
20 var $ps_slider      = $('#ps_slider');

We are going to give an initial positioning to the album columns:

01 /**
02 * position all the albums on the right side of the window
03 */
04 var hiddenRight     = $(window).width() - $ps_albums.offset().left;
05 $ps_albums.children('div').css('left',hiddenRight + 'px');
06
07 /**
08 * move the first 5 albums to the viewport
09 */
10 $ps_albums.children('div:lt(5)').each(
11 function(i){
12 var $elem = $(this);
13 $elem.animate({'left': positions[i] + 'px','opacity':1},800,function(){
14 if(elems > 5)
15 enableNavRight();
16 });
17 }
18 );

For sliding through the albums, we will define what happens when we click on the next or previous button and create two functions for moving left or right:

01 /**
02 * next album
03 */
04 $ps_slider.find('.next').bind('click',function(){
05 if(!$ps_albums.children('div:nth-child('+parseInt(first+5)+')').length || !navR) return;
06 disableNavRight();
07 disableNavLeft();
08 moveRight();
09 });
10
11 /**
12 * we move the first album (the one on the left) to the left side of the window
13 * the next 4 albums slide one position, and finally the next one in the list
14 * slides in, to fill the space of the first one
15 */
16 function moveRight () {
17 var hiddenLeft  = $ps_albums.offset().left + 163;
18
19 var cnt = 0;
20 $ps_albums.children('div:nth-child('+first+')').animate({'left': - hiddenLeft + 'px','opacity':0},500,function(){
21 var $this = $(this);
22 $ps_albums.children('div').slice(first,parseInt(first+4)).each(
23 function(i){
24 var $elem = $(this);
25 $elem.animate({'left': positions[i] + 'px'},800,function(){
26 ++cnt;
27 if(cnt == 4){
28 $ps_albums.children('div:nth-child('+parseInt(first+5)+')').animate({'left': positions[cnt] + 'px','opacity':1},500,function(){
29 //$this.hide();
30 ++first;
31 if(parseInt(first + 4) < elems)
32 enableNavRight();
33 enableNavLeft();
34 });
35 }
36 });
37 }
38 );
39 });
40 }
41
42 /**
43 * previous album
44 */
45 $ps_slider.find('.prev').bind('click',function(){
46 if(first==1  || !navL) return;
47 disableNavRight();
48 disableNavLeft();
49 moveLeft();
50 });
51
52 /**
53 * we move the last album (the one on the right) to the right side of the window
54 * the previous 4 albums slide one position, and finally the previous one in the list
55 * slides in, to fill the space of the last one
56 */
57 function moveLeft () {
58 var hiddenRight     = $(window).width() - $ps_albums.offset().left;
59
60 var cnt = 0;
61 var last= first+4;
62 $ps_albums.children('div:nth-child('+last+')').animate({'left': hiddenRight + 'px','opacity':0},500,function(){
63 var $this = $(this);
64 $ps_albums.children('div').slice(parseInt(last-5),parseInt(last-1)).each(
65 function(i){
66 var $elem = $(this);
67 $elem.animate({'left': positions[i+1] + 'px'},800,function(){
68 ++cnt;
69 if(cnt == 4){
70 $ps_albums.children('div:nth-child('+parseInt(last-5)+')').animate({'left': positions[0] + 'px','opacity':1},500,function(){
71 //$this.hide();
72 --first;
73 enableNavRight();
74 if(first > 1)
75 enableNavLeft();
76 });
77 }
78 });
79 }
80 );
81 });
82 }

The next helper functions deal with disabling and enabling the the navigation items:

01 /**
02 * disable or enable albums navigation
03 */
04 function disableNavRight () {
05 navR = false;
06 $ps_slider.find('.next').addClass('disabled');
07 }
08 function disableNavLeft () {
09 navL = false;
10 $ps_slider.find('.prev').addClass('disabled');
11 }
12 function enableNavRight () {
13 navR = true;
14 $ps_slider.find('.next').removeClass('disabled');
15 }
16 function enableNavLeft () {
17 navL = true;
18 $ps_slider.find('.prev').removeClass('disabled');
19 }

In the next steps we will define what happens when we open an album. We first make the loading element appear and show the preview after we loaded all the images. The information of the source comes from an AJAX call to our PHP class. For the rotation effect, we use the rotate CSS3 property which we restrict to a certain range of degrees, so that we don’t rotate an image crazily:

01 var $ps_container   = $('#ps_container');
02 var $ps_overlay     = $('#ps_overlay');
03 var $ps_close       = $('#ps_close');
04 /**
05 * when we click on an album,
06 * we load with AJAX the list of pictures for that album.
07 * we randomly rotate them except the last one, which is
08 * the one the User sees first. We also resize and center each image.
09 */
10 $ps_albums.children('div').bind('click',function(){
11 var $elem = $(this);
12 var album_name  = 'album' + parseInt($elem.index() + 1);
13 var $loading    = $('<div />',{className:'loading'});
14 $elem.append($loading);
15 $ps_container.find('img').remove();
16 $.get('photostack.php', {album_name:album_name} , function(data) {
17 var items_count = data.length;
18 for(var i = 0; i < items_count; ++i){
19 var item_source = data[i];
20 var cnt         = 0;
21 $('<img />').load(function(){
22 var $image = $(this);
23 ++cnt;
24 resizeCenterImage($image);
25 $ps_container.append($image);
26 var r       = Math.floor(Math.random()*41)-20;
27 if(cnt < items_count){
28 $image.css({
29 '-moz-transform' :'rotate('+r+'deg)',
30 '-webkit-transform' :'rotate('+r+'deg)',
31 'transform' :'rotate('+r+'deg)'
32 });
33 }
34 if(cnt == items_count){
35 $loading.remove();
36 $ps_container.show();
37 $ps_close.show();
38 $ps_overlay.show();
39 }
40 }).attr('src',item_source);
41 }
42 },'json');
43 });
44
45 /**
46 * when hovering each one of the images,
47 * we show the button to navigate through them
48 */
49 $ps_container.live('mouseenter',function(){
50 $('#ps_next_photo').show();
51 }).live('mouseleave',function(){
52 $('#ps_next_photo').hide();
53 });

The nice animation of putting the current image at the back of our stack is defined in the following:

01 /**
02 * navigate through the images:
03 * the last one (the visible one) becomes the first one.
04 * we also rotate 0 degrees the new visible picture
05 */
06 $('#ps_next_photo').bind('click',function(){
07 var $current    = $ps_container.find('img:last');
08 var r           = Math.floor(Math.random()*41)-20;
09
10 var currentPositions = {
11 marginLeft  : $current.css('margin-left'),
12 marginTop   : $current.css('margin-top')
13 }
14 var $new_current = $current.prev();
15
16 $current.animate({
17 'marginLeft':'250px',
18 'marginTop':'-385px'
19 },250,function(){
20 $(this).insertBefore($ps_container.find('img:first'))
21 .css({
22 '-moz-transform' :'rotate('+r+'deg)',
23 '-webkit-transform' :'rotate('+r+'deg)',
24 'transform' :'rotate('+r+'deg)'
25 })
26 .animate({
27 'marginLeft':currentPositions.marginLeft,
28 'marginTop' :currentPositions.marginTop
29 },250,function(){
30 $new_current.css({
31 '-moz-transform' :'rotate(0deg)',
32 '-webkit-transform' :'rotate(0deg)',
33 'transform' :'rotate(0deg)'
34 });
35 });
36 });
37 });

We animate the top and left margins with certain values that create the “putting back” effect. Since our structure always shows the last image on the top, we will also need to insert the moving image at the beginning, so that it appear as last one in the stack.

Clicking on the close element brings us back to the album view:

1 /**
2 * close the images view, and go back to albums
3 */
4 $('#ps_close').bind('click',function(){
5 $ps_container.hide();
6 $ps_close.hide();
7 $ps_overlay.fadeOut(400);
8 });

Our famous resize function resizes the image according to the given container width and height.
In the end of the function we apply the sizes and we also apply the negative margins – remember, that’s the way we can center an absolute positioned element; we defined top and left in the CSS to be 50%, so now we need to pull it to the right place with these margin values.

01 /**
02 * resize and center the images
03 */
04 function resizeCenterImage($image){
05 var theImage    = new Image();
06 theImage.src    = $image.attr("src");
07 var imgwidth    = theImage.width;
08 var imgheight   = theImage.height;
09
10 var containerwidth  = 460;
11 var containerheight = 330;
12
13 if(imgwidth > containerwidth){
14 var newwidth = containerwidth;
15 var ratio = imgwidth / containerwidth;
16 var newheight = imgheight / ratio;
17 if(newheight > containerheight){
18 var newnewheight = containerheight;
19 var newratio = newheight/containerheight;
20 var newnewwidth =newwidth/newratio;
21 theImage.width = newnewwidth;
22 theImage.height= newnewheight;
23 }
24 else{
25 theImage.width = newwidth;
26 theImage.height= newheight;
27 }
28 }
29 else if(imgheight > containerheight){
30 var newheight = containerheight;
31 var ratio = imgheight / containerheight;
32 var newwidth = imgwidth / ratio;
33 if(newwidth > containerwidth){
34 var newnewwidth = containerwidth;
35 var newratio = newwidth/containerwidth;
36 var newnewheight =newheight/newratio;
37 theImage.height = newnewheight;
38 theImage.width= newnewwidth;
39 }
40 else{
41 theImage.width = newwidth;
42 theImage.height= newheight;
43 }
44 }
45 $image.css({
46 'width' :theImage.width,
47 'height' :theImage.height,
48 'margin-top' :-(theImage.height/2)-10+'px',
49 'margin-left' :-(theImage.width/2)-10+'px'
50 });
51 }
52 });

And that’s it! We hope you enjoyed this tutorial and find it useful!

P.S. Because of some Webkit properties, this demo is a really nice experience if you use a Webkit browser like Chrome or Safari. It will also be fully functional in all latest browsers like Firefox and IE (without those beautiful properties, though).