CSS-2 ways to build parallax effect

What is parallax

Parallax is an effect where the background layer or image in this case, is moved at a different speed than the front layer while scrolling.

Parallax design is a popular technique in modern webdesign. There are two approaches to this effect: CSS and JS. Both are really easy. So here we go

CSS Approach

For your background image, you need to make the background-attachment property fixed. This will set whether the background image is fixed or scrolls with the rest of the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<style>
.parallax {
/* The image used */
background-image: url("img_parallax.jpg");

/* Set a specific height */
height: 500px;

/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>

<!-- Container element -->
<div class="parallax"></div>

Here’s a demo of how the site will work. My Github Demo

JS Approach

In your html section add data-type and data-speed attribute. The speed will adjust the speed of how the background move.

Markup

1
2
3
4
5
6
7
<section id="home" data-type="background" data-speed="10">
<article>I am absolute positioned</article>
</section>

<section id="about" data-type="background" data-speed="10">
<article>Simple Parallax Scroll</article>
</section>

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
#home {
background: url(home-bg.jpg) 50% 0 repeat fixed; min-height: 1000px;
height: 1000px;
margin: 0 auto;
width: 100%;
max-width: 1920px;
position: relative;
}

#home article {
height: 458px;
position: absolute;
text-align: center;
top: 150px;
width: 100%;
}

#about {
background: url(about-bg.jpg) 50% 0 repeat fixed; min-height: 1000px;
height: 1000px;
margin: 0 auto;
width: 100%;
max-width: 1920px;
position: relative;
-webkit-box-shadow: 0 0 50px rgba(0,0,0,0.8);
box-shadow: 0 0 50px rgba(0,0,0,0.8);
}

#about article {
height: 458px;
position: absolute;
text-align: center;
top: 150px;
width: 100%;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
$('section[data-type="background"]').each(function(){
var $bgobj = $(this); // assigning the object

$(window).scroll(function() {
var yPos = -($window.scrollTop() / $bgobj.data('speed'));

// Put together our final background position
var coords = '50% '+ yPos + 'px';

// Move the background
$bgobj.css({ backgroundPosition: coords });
});
});
});

The concept of this code is illusrated in this image.
Alt text