首页 > 技术文章 > 纯css滚动视差

e-cat 2018-08-13 10:36 原文

1.何为滚动视差

视差滚动(Parallax Scrolling)是指让多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验。 作为网页设计的热点趋势,越来越多的网站应用了这项技术。效果如图:

一般而言,滚动视差在前端需要辅助 Javascript 才能实现。当然,其实 CSS 在实现滚动视差效果方面,也有着不俗的能力。

2.认识 background-attachment

background-attachment:如果指定了 background-image ,那么 background-attachment 决定背景是在视口中固定的还是随着包含它的区块滚动的。

(1)background-attachment: scroll

scroll 此关键字表示背景相对于元素本身固定, 而不是随着它的内容滚动。

(2)background-attachment: local

local 此关键字表示背景相对于元素的内容固定。如果一个元素拥有滚动机制,背景将会随着元素的内容滚动, 并且背景的绘制区域和定位区域是相对于可滚动的区域而不是包含他们的边框。

(3)background-attachment: fixed

fixed 此关键字表示背景相对于视口固定。即使一个元素拥有滚动机制,背景也不会随着元素的内容滚动。

注意一下 scroll 与 fixed,一个是相对元素本身固定,一个是相对视口固定,有点类似 position 定位的 absolute 和 fixed。

 CodePen Demo — bg-attachment Demo(https://codepen.io/Chokcoco/pen/xJJorg

3.代码实现

html:

1   <section class="g-word">Header</section>
2   <section class="g-img g-img-1">IMG1</section>
3   <section class="g-word">Content1</section>
4   <section class="g-img g-img-2">IMG2</section>
5   <section class="g-word">Content2</section>
6   <section class="g-img g-img-3">IMG3</section>
7   <section class="g-word">Footer</section>

css:

 1     * {
 2       padding: 0;
 3       margin: 0;
 4     }
 5 
 6     section {
 7       height: 100vh;
 8       line-height: 100vh;
 9       text-align: center;
10       font-size: 50px;
11       font-weight: bold;
12     }
13 
14     .g-img {
15       background-attachment: fixed;
16       background-size: cover;
17       background-position: center center;
18     }
19 
20     .g-img-1 {
21       background-image: url('./image/01.jpg');
22     }
23 
24     .g-img-2 {
25       background-image: url('./image/02.jpg');
26     }
27 
28     .g-img-3 {
29       background-image: url('./image/03.jpg');
30     }

图片资源自行填充。

至此,css滚动视差效果制作完成。

推荐阅读