CSS之滚动视差

什么是滚动视差?

滚动视差是指让多层背景以不同的速度移动,形成立体的运动效果。

大多数情况下,我们要完成一个滚动视差的页面需要js来辅助,但是css也可以起到相同的作用。

在css中有一个background-attachment属性,这个属性比较陌生。

background-attachment支持以下关键字:

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

local:相对于元素的内容固定。

fixed:相对于视口固定。

例子:

html代码:

<section class="g-word">
    <div>
      人总归是人,当一个人激情澎湃而又受到人性局限的逼迫时,他即使有哪么点理性也很少起作用或者根本不起作用。
    </div>
</section>
<section class="g-img">
    <div>we need to learn how to steer by our inner compass and trust it more than we ever have before.
    </div>
</section>
<section class="g-word">
    <div>we need to learn how to steer by our inner compass and trust it more than we ever have before.
    <br>
        Life is short and you deserve to be happy.
    <br>
        生命苦短,你应该过得开心些。
    </div>
</section>
<section class="g-img1">
    <div>Distance makes the hearts grow fonder.
    <br>
        距离会使两颗心靠的更近。
    </div>
</section>
<section class="g-word">
    <div>
        从白天到黑夜 你牵动我的心<br>
        成为我平日里 最盛大的欢喜<br>
        就算你又出现在梦里<br>
        睁眼还是很想你<br>
        你就想清晨第一口水很甜<br>
        让我沐浴在你给我的新鲜
    </div>
</section>
<section class="g-img2">
    <div>
        I love you three things in this word.Sun,moon and you.Sun for morning,moon for night,and you forever.
    <br>
        予独爱世间三物。昼之日,夜之月,汝之永恒。
    </div>
</section>
<section class="g-word"><div>I love you three things in this word.Sun,moon and you.Sun for morning,moon for night.we need to learn how to steer by our inner compass and trust it more than we ever have.
</div></section>
<section class="g-img3"><div>
    You know my loneliness is only kept for you,my sweet songs are only sung for you.
<br>你可知我百年的孤寂只为你一人守候,千年的恋歌只为你一人唱。</div>
</section>

css代码:

    section{
        height: 100vh;
    }
    .g-img{
        background-image: url("img/woman.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
    }
    .g-img1{
        background-image: url("img/man.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
    }
    .g-img2{
        background-image: url("img/ice.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
    }
    .g-img3{
        background-image: url("img/sea.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
    }
    .g-word{
        background-color: #dddddd;
    }
    div{
        padding-top: 30vmin;
        padding-left: 15vmin;
        color: #333344;
        font-size: 4vmin;
    }
</style>

效果图:

猜你喜欢

转载自blog.csdn.net/The_upside_of_down/article/details/82749299