天天看點

[css] 小案例---滾動吸頂

position:sticky;是粘性定位,專門用于頁面滾動的時候的定位,可以友善實作吸頂條的效果。

粘性定位是相對定位和固定定位的混合。元素在跨越特定門檻值前為相對定位(relative),之後為固定定位(fixed)

#box { position: sticky; top: 10px; }
           
<!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>
        *{
            margin: 0;
            padding: 0;
        }

        header,footer{
            height: 30px;
            background-color: rgb(218, 143, 143);
            text-align: center;
        }
        nav{
            height: 20px;
            background-color: rgb(144, 179, 233);
            text-align: center;
            position: sticky;
            top: 10px;
        }
        section{
            height: 1200px;
            background-color: rgb(212, 24, 24);
            text-align: center;
            font-size: 50px;

        }

    </style>
</head>
<body>
    <header>頭部</header>
    <nav>導航</nav>
    <section>主體</section>
    <footer>尾部</footer>
</body>
</html>
           

使用條件:

  • 父元素不能overflow:hidden或者overflow:auto屬性。
  • 必須指定top、bottom、left、right4個值之一,否則隻會處于相對定位。
  • 父元素的高度不能低于sticky元素的高度。
  • sticky元素僅在其父元素内生效。