简体   繁体   中英

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: 在此处输入图片说明

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM