css 吸顶 [position:sticky;]

246 阅读1分钟

话不多说,上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .extra{
            background: gray;
            height: 200px;
        }
        .header{
            height: 100px;
            background-color: blue;
            position: sticky;
            top: 50px;
            color: #ffffff;
        }
        .body{
            height: 2000px;
            background: red;
        }
        .item{
            background: green;
            height: 100px;
            margin-top: 20px;
            color:#ffffff;

        }
    </style>
</head>
<body>
    <div class="extra">
        这是一段额外的内容
    </div>
    <div class="header">
        这是header内容
    </div>
    <div class="body">
        <div class="item">
            这是item
        </div>
        <div class="item">
            这是item
        </div>
        <div class="item">
            这是item
        </div>
        <div class="item">
            这是item
        </div>
    </div>
</body>
</html>

效果

注意点

  • 该元素并不脱离文档流,仍然保留元素原本在文档流中的位置。
  • 当元素在容器中被滚动超过指定的偏移值时,元素在容器内固定在指定位置。亦即如果你设置了top: 50px,那么在sticky元素到达距离相对定位的元素顶部50px的位置时固定,不再向上移动。
  • 元素固定的相对偏移是相对于离它最近的具有滚动框的祖先元素,如果祖先元素都不可以滚动,那么是相对于viewport来计算元素的偏移量