首页 > 网站优化 > css

CSS制作的页面背景固定和滚动效果

发布时间:2016-9-14 14:19

背景固定效果在许多的网站都能看到,今天我们一起来看一个关于CSS制作的页面背景固定和滚动效果,应用非常的好用希望对各位带来帮助。

如何创建一个不需要Javascript而仅仅只需CSS的background-attachment属性就能实现页面背景固定和滚动效果。我们看到现在有很多的网站项目使用了视差效果,通过图片和背景的动态变化以及js脚本来产生视差,而今天我们只需要CSS即可。


HTML结构很简单,一个class为.cd-fixed-bg的div元素用于放置固定背景图,一个class为.cd-scrolling-bg的div元素用于滚动的部分。我们可以放置多个.cd-fixed-bg和.cd-scrolling-bg编组。

 代码如下 复制代码

<main>
    <div class="cd-fixed-bg cd-bg-1">
        <h1><!-- title goes here --></h1>
    </div> 
 
    <div class="cd-scrolling-bg cd-color-2">
        <div class="cd-container">
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore incidunt suscipit similique, dolor corrupti cumque qui consectetur autem laborum fuga quas ipsam doloribus sequi...
            </p>
        </div> 
    </div> 
    ...多组div并列...
</main>

CSS

那么如何实现背景固定和滚动效果呢?一开始,我想使用jQuery,也许我先应该让一个div固定位置,然后当滚动页面时改变背景图片,但是觉得不好弄。而简单的我们使用几行CSS就能做到,将要固定的元素的背景background-size值设置为cover,background-attachment的值设置为fixed,这样就实现了单页面的背景固定和滚动效果。请看以下代码:

 代码如下 复制代码

body, html, main {
    /* important */
    height: 100%;
}
 
.cd-fixed-bg {
    min-height: 100%;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center center;
}
 
.cd-fixed-bg.cd-bg-1 {
  background-image: url("../img/cd-background-1.jpg");
}
.cd-fixed-bg.cd-bg-2 {
  background-image: url("../img/cd-background-2.jpg");
}
.cd-fixed-bg.cd-bg-3 {
  background-image: url("../img/cd-background-3.jpg");
}
 
 
.cd-scrolling-bg {
    min-height: 100%;
}

标签:[!--infotagslink--]

您可能感兴趣的文章: