css粘性定位position:sticky

786 阅读1分钟

介绍

position:sticky是css定位新增属性;可以说是相对定位relative和固定定位fixed的结合;它主要用在对scroll事件的监听上;简单来说,在滑动过程中,某个元素距离其父元素的距离达到sticky粘性定位的要求时(比如top:100px);position:sticky这时的效果相当于fixed定位,固定到适当位置。

使用条件

  1. 父元素不能overflow:hidden或者overflow:auto属性。
  2. 必须指定top、bottom、left、right4个值之一,否则只会处于相对定位
  3. 父元素的高度不能低于sticky元素的高度
  4. sticky元素仅在其父元素内生效
  nav{
    position: sticky;
    top: 0;
  }

全部代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/index1.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
    <style>
        body{
            overflow: scroll;
        }
        nav{
            position: sticky;
            top: 0;
            display: flex;
            justify-content: space-between;
            background: green;
        }
        h3{
            font-size: 20px;
            color: white;
        }
        ul li{
            line-height: 150px;
            height: 150px;
            font-size: 20px;
            border-bottom: 1px solid orange;
            list-style: none;
        }
    </style>
</head>
<body>
    <h1>我是position: sticky的第一个demo</h1>
    <nav>
        <h3>导航A</h3>
        <h3>导航B</h3>
        <h3>导航C</h3>
    </nav>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
    </ul>
</body>
</html>