Search code examples
javascripthtmlcsscss-animationsparallax

Creating a parallax-like effect using an image that isn't the background


I'm trying to create a scrolling effect that preferably doesn't use javascript (CSS only) but I understand if it's not possible, just exploring options.

My page looks like this: enter image description here

When scrolling down I want the background image to have a parallax-like effect, staying static while the body's background and frame move around it.

Here's a sample of code to work with:

http://jsfiddle.net/J8fFa/7/

HTML

<body>
    <div class="border-bg">
        <div class="image-bg"></div>
    </div>
    <div class="border-bg">
        <div class="spacer">
        </div>
    </div>
</body>

CSS

body{
    background-color:#aaa;
}

.border-bg{
    width:80%;
    margin:30px auto;
    background-color:#fff;
    padding:40px;
}

.image-bg{
     background:url('http://i.imgur.com/7cM1oL6.jpg');   
    height:400px;
        background-size:cover;
}

.spacer{
    height:900px;
}

I can see how this would work if the image was the background for the body, but as this is sitting on top of the body is there any way I can manipulate it to have a similar visual effect?


Solution

  • change your .image-bg class to:

    .image-bg{
         background:url('http://i.imgur.com/7cM1oL6.jpg') fixed;   
        height:400px;
            background-size:cover;
    }
    

    this will prevent the image from scrolling

    updated fiddle: http://jsfiddle.net/J8fFa/9/