1

position: sticky; top:0;功能:
1)正常情况下, sticky元素在页面中正常布局;
2)当sticky元素顶部距离浏览器页面顶部为设定值(此处为0)时, 表现得像fixed;
3)当sticky元素底部与包裹它的容器底部相触时, 恢复正常;
以下示意图可以更好的感受到它的效果:

demo代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .container {
            position: relative;
            margin: 0 auto;
            width: 500px;
            height: 2500px;
            background-color: red;
        }
        .footer {
            position: relative;
            margin: 0 auto;
            width: 500px;
            height: 2500px;
            background-color: rgb(76, 31, 160);
        }
        .header {
            width: 300px;
            height: 500px;
            margin: 0 auto 20px;
            background-color: green;
        }
        .content {
            position: sticky;
            top: 0;
            height: 220px;
            width: 300px;
            margin: 0 auto;
            background-color: rgb(90, 79, 238);
        }
    </style>
</head>

<body>
    <body>
        <div class="container">
            <div class="header">header</div>
            <div class="content">content</div>
        </div>
        <div class="footer">footer</div>
    </body>
    <script>
    </script>
</body>

</html>

小飞2020
18 声望4 粉丝

相信自己, 慢慢变强