Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background image that moves when you scroll down the page

Tags:

html

css

I keep seeing websites with a background image that subtly moves when you scroll down. This is a really nice effect but I'm not sure how to do this? I'm am experienced with html, css and jquery but this is something I haven't done before!

I have a simple jsfiddle below but I need some help please!

Many thanks,

http://jsfiddle.net/def2y2yt/

Code snippet - more available using the jsfiddle link

.background {
    background-image: url(example.pjg);
    background-repeat: no-repeat;
    height: 600px;
    width: 100%;
}
like image 610
user3773890 Avatar asked Aug 18 '14 18:08

user3773890


People also ask

What is a parallax image?

Parallax scrolling is a web site trend where the background content (i.e. an image) is moved at a different speed than the foreground content while scrolling.

How do I change my background while scrolling?

Set the background-size to "cover" to scale the images as large as possible to cover all the background area. Add links of the images with the background-image property. Style the content giving it a border and setting the width and height of it. Set the position to "fixed" so as it will be fixed while scrolling.

What feature is used to control the scrolling of an image in the background?

To set the scrolling of an image in the background, use the background-attachment property.

What is background-attachment scroll?

The background-attachment property is used to specify that the background image is fixed or scroll with the rest of the page in the browser window. This property has three values scroll, fixed, and local. Its default value is scroll, which causes the element to not scroll with its content.


2 Answers

Like TylerH said, it's called Parallax. You can see an example here.

Using JavaScript:

var velocity = 0.5;

function update(){ 
var pos = $(window).scrollTop(); 
$('.container').each(function() { 
    var $element = $(this);
    // subtract some from the height b/c of the padding
    var height = $element.height()-18;
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) +  'px'); 
   }); 
   };

 $(window).bind('scroll', update);
like image 112
Sam Avatar answered Nov 15 '22 13:11

Sam


Or you could use this simple CSS property which I made a blog post about: http://nathanpeixoto.fr/blog/article8/web-un-one-page-presque-sans-javascript (French only, sorry).

Let's say this is your HTML:

<div class="background_container">

</div>
<style>
.background_container{
  background-image: url("XXX");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed; /* <= This one */
}
</style>
like image 40
Nathan Peixoto Avatar answered Nov 15 '22 15:11

Nathan Peixoto