纯css滚动视差

时间:2021-01-12 14:41:56

1.何为滚动视差

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

纯css滚动视差

一般而言,滚动视差在前端需要辅助 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:

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

css:

 1     * {
padding:;
margin:;
} section {
height: 100vh;
line-height: 100vh;
text-align: center;
font-size: 50px;
font-weight: bold;
} .g-img {
background-attachment: fixed;
background-size: cover;
background-position: center center;
} .g-img-1 {
background-image: url('./image/01.jpg');
} .g-img-2 {
background-image: url('./image/02.jpg');
} .g-img-3 {
background-image: url('./image/03.jpg');
}

图片资源自行填充。

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