如何使用css实现滚动贴合

网页开发一直在不断的发展,特效也是越来越多。我们经常见到的很多网站会在鼠标滚动的时候,页面会自动贴合到浏览器的顶部或者底部,例如特斯拉的官网这样,使用这种展示方式,既可以突出产品又显得非常酷炫。

以前实现这种滚动特效一般都是通过javascript实现的,现在通过css原生属性就可以实现。而且不论在移动端还是桌面端都可以达到操作系统级别的滚动效果。

css属性

设置css滚动贴合要使用到两个属性

1、给滚动的容器设置 scroll-snap-type 属性

2、给滚动的内容设置 scroll-snap-align 属性

.container{ 
    scroll-snap-type: y mandatory; 
}
.child{
    scroll-snap-align: start;
}

这样就可以实现滚动贴合的效果了。

示例代码

了解了要用到的css属性后,简单的写一个代码来演示一下效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>css实现滚动贴合</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        main{
            width: 100vw;
            height: 100vh;
            scroll-snap-type: y mandatory;
            overflow: scroll;
            height: 100vh;
        }
        section{
            scroll-snap-align: center;
            width: 100vw;
            height: 100vh;
            line-height: 100vh;
            text-align: center;
            font-size: 25px;
            font-weight: bold;
        }
        /* 给每个页面设置不同的颜色用于区分 */
        main > section:nth-child(1){
            background-color: #7f97ae;
        }
        main > section:nth-child(2){
            background-color: #c6b9a3;
        }
        main > section:nth-child(3){
            background-color: #bbcadc;
        }
        main > section:nth-child(4){
            background-color: #d7c6d9;
        }
        main > section:nth-child(5){
            background-color: #bfbea8;
        }
    </style>
</head>
<body>
    <main>
        <section>第一页</section>
        <section>第二页</section>
        <section>第三页</section>
        <section>第四页</section>
        <section>第五页</section>
    </main>
</body>
</html>

运行这个网页,可以看到这样的效果,就实现了使用css做滚动贴合的效果

本文由:小天丶 发布于 小菜的IT网,转载请注明出处:https://www.xiaocaiit.cn/844.html

相关推荐

评论此文章

已有0人参与了评论