何为滚动视差
视差滚动(Parallax Scrolling)是指让多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验。 作为网页设计的热点趋势,越来越多的网站应用了这项技术。
通常而言,滚动视差在前端需要辅助 Javascript 才能实现。当然,其实 CSS 在实现滚动视差效果方面,也有着不俗的能力。下面就让我们来见识一二:
认识 background-attachment
background-attachment
算是一个比较生僻的属性,基本上平时写业务样式都用不到这个属性。但是它本身很有意思。
background-attachment
:如果指定了 background-image
,那么 background-attachment
决定背景是在视口中固定的还是随着包含它的区块滚动的。
单单从定义上有点难以理解,随下面几个 Demo 了解下 background-attachment
到底是什么意思:
background-attachment: scroll
scroll 此关键字表示背景相对于元素本身固定, 而不是随着它的内容滚动。
background-attachment: local
local 此关键字表示背景相对于元素的内容固定。如果一个元素拥有滚动机制,背景将会随着元素的内容滚动, 并且背景的绘制区域和定位区域是相对于可滚动的区域而不是包含他们的边框。
background-attachment: fixed
fixed 此关键字表示背景相对于视口固定。即使一个元素拥有滚动机制,背景也不会随着元素的内容滚动。
注意一下 scroll 与 fixed,一个是相对元素本身固定,一个是相对视口固定,有点类似 position
定位的 absolute
和 fixed
。
<section class="g-word">Header</section> <section class="g-img1">IMG1</section> <section class="g-word">Content1</section> <section class="g-img2">IMG2</section> <section class="g-word">Content2</section> <section class="g-img3">IMG3</section> <section class="g-word">Footer</section>
$img1: 'http://pic7.photophoto.cn/20080407/0034034859692813_b.jpg'; $img2: 'http://up.enterdesk.com/edpic_source/21/00/00/210000f8e772d7fc0758e67ae4b48807.jpg'; $img3: 'https://images.unsplash.com/photo-1440688807730-73e4e2169fb8?dpr=1&auto=format&fit=crop&w=1500&h=1001&q=80&cs=tinysrgb&crop='; section { height: 100vh; background: rgba(0, 0, 0, .7); color: #fff; line-height: 100vh; text-align: center; font-size: 20vh; } .g-img1 { background-image: url($img1); background-attachment: fixed; background-size: cover; background-position: center center; } .g-img2 { background-image: url($img2); background-attachment: fixed; background-size: cover; background-position: center center; } .g-img3 { background-image: url($img3); background-attachment: fixed; background-size: cover; background-position: center center; }
效果如下:
转载:https://www.cnblogs.com/coco1s/p/9453938.html