position sticky 定位

1、兼容性

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

chrome、ios和firefox兼容性良好。

2、使用场景

sticky:粘性。粘性布局。

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

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

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

扫描二维码关注公众号,回复: 3985037 查看本文章

示例一:

<!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>

效果:

猜你喜欢

转载自www.cnblogs.com/mengfangui/p/9929198.html
今日推荐