position sticky 定位

Posted mengfangui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了position sticky 定位相关的知识,希望对你有一定的参考价值。

1、兼容性

https://caniuse.com/#search=sticky

技术分享图片

chrome、ios和firefox兼容性良好。

 

2、使用场景

sticky:粘性。粘性布局。

在屏幕范围内时,元素不受定位影响(即top、left等设置无效);

当元素的位置将要移出偏移范围时,定位又会变成fixed,根据设置的left、top等属性成固定位置的效果。

说明:元素并没有脱离文档流

 

示例一:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>position:sticky示例</title>
        <style type="text/css">
            .container {
                background: #eee;
                width: 600px;
                height: 10000px;
                margin: 0 auto;
            }

            .sticky-box {
                position: -webkit-sticky;
                position: sticky;
                height: 60px;
                margin-bottom: 30px;
                background: #ff7300;
                top: 0px;
            }

            div {
                font-size: 30px;
                text-align: center;
                color: #fff;
                line-height: 60px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="sticky-box">内容1</div>
            <div class="sticky-box">内容2</div>
            <div class="sticky-box">内容3</div>
            <div class="sticky-box">内容4</div>
        </div>
    </body>
</html>

效果:

技术分享图片

示例二:实现头部固定的导航栏

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>position:sticky示例</title>
        <style type="text/css">
            .container {
                background: #eee;
                width: 600px;
                height: 10000px;
                margin: 0 auto;
            }

            nav {
                position: -webkit-sticky;
                position: sticky;
                top: 0;

            }

            nav {
                height: 50px;
                background: #999;
                color: #fff;
                font-size: 30px;
                line-height: 50px;
            }

            .content {
                margin-top: 30px;
                background: #ddd;
            }

            p {
                line-height: 40px;
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <nav>我是导航栏</nav>
            <div class="content">
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
                <p>我是内容栏</p>
            </div>
        </div>
    </body>
</html>

效果:

技术分享图片

以上是关于position sticky 定位的主要内容,如果未能解决你的问题,请参考以下文章

彻底理解粘性定位 - position: sticky

position sticky 定位

position的sticky与fixed

CSS:position:sticky;不生效的原因

JS简单实现“滚动到顶部“按钮悬浮效果,在一定高度才显示 - 替代CSS粘性定位position:sticky方案

JS简单实现“滚动到顶部“按钮悬浮效果,在一定高度才显示 - 替代CSS粘性定位position:sticky方案