Sky Blue Sofa Blog Adding a Parallax Background to Your Site - Sky Blue Sofa Blog

Adding a Parallax Background to Your Site

Posted by Dave Rogers // December 5, 2012 // in Blog // 0 Comments

Parallax Feature Image

As I was updating my company's website, skybluesofa.com, I thought that it was a bit, well, flat. The site needed a bit of pizzaz; not over the top, just a little dash.

I'd recently read some posts about a concept called 'parallax'. The basic concept of parallax is that things closer to you move faster than things that are farther away. Think about that time you were taking a road trip and watching the telephone poles quickly go by. The fields behind them went just a bit slower and the hills in the distance went slowest of all. That's parallax.

Initially, the design just had a background image of clouds at the top of the page, as you can see in this image:

Parallax 1

What I wanted to do is to have another bank of clouds fade in as the user scrolled the page. Here you can see the second cloud image coming out from behind the first:

Parallax 2

How it Works

The HTML Markup

To do this, I added two DIV tags just after the opening BODY tag:

  1. <div id="background_image"></div>
  2. <div id="background_image2"></div>

The CSS

And I styled these DIVs with this CSS, which places them both at the top of the page. The opacity on the second DIV is set to zero, to hide it from showing up.

  1. #container {
  2. position:absolute;
  3. top:0; left:0; right:0;
  4. z-index:4
  5. }
  6. #background_image {
  7. background:url(clouds.png) repeat-x left;
  8. position:absolute;
  9. top:0; left:0; right:0;
  10. height:400px;
  11. z-index:3;
  12. }
  13. #background_image2 {
  14. background:url(clouds.png) repeat-x bottom center;
  15. position:absolute;
  16. top:0; left:0; right:0;
  17. height:500px;
  18. z-index:2;
  19. opacity:0;
  20. }

The JavaScript

Then I added a bit of jQuery magic by tapping into the onScroll event of the window.

  1. <script>
  2. $(window).bind("scroll",function(e){
  3. parallaxScroll();
  4. });
  5.  
  6. function parallaxScroll(){
  7. var scrolled = $(window).scrollTop();
  8. $("#background_image").css("top",(0+(scrolled*.6))+"px");
  9. $("#background_image2").css("top",(0+(scrolled*.8))+"px");
  10. $("#background_image2").css("opacity",(0+(scrolled*.08))/100);
  11. }
  12. </script>

Hope this helps someone. Let me know if you found it useful.

About the Author

Dave Rogers

Dave is the founder of Sky Blue Sofa Web Design. He enjoys working out, spending time with his wife and dogs and programming. He grew up and currently resides in the Illinois Quad Cities. You can find his personal blog at strength/reliance.com.

View Profile »

Comments

You must be logged in to leave a reply. Login »