生效规则

position:sticky 的生效是有一定的限制的,总结如下:

  1. 须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。

    • 并且 top 和 bottom 同时设置时,top 生效的优先级高,left 和 right 同时设置时,left 的优先级高。
  2. 设定为 position:sticky 元素的任意父节点的 overflow 属性必须是 visible,否则 position:sticky 不会生效。这里需要解释一下:

    • 如果 position:sticky 元素的任意父节点定位设置为 overflow:hidden,则父容器无法进行滚动,所以 position:sticky 元素也不会有滚动然后固定的情况。
    • 如果 position:sticky 元素的任意父节点定位设置为 position:relative | absolute | fixed,则元素相对父元素进行定位,而不会相对 viewprot 定位。
  3. 达到设定的阀值。这个还算好理解,也就是设定了 position:sticky 的元素表现为 relative 还是 fixed 是根据元素是否达到设定了的阈值决定的。

position:sticky;粘性布局

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>position:sticky;粘性布局</title>
  <style>
    *{margin:0;padding:0;}
    .box{
      height:2000px;
      overflow: visible;
    }
    .item{
      position:sticky;
      top:0;
      height:240px;
      transition: all 2s;
      background:red;
      line-height:240px;
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
  </div>
</body>
</html>

 

相关文章:

  • 2021-04-07
  • 2021-06-25
  • 2022-01-14
  • 2021-04-20
  • 2022-02-05
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-15
  • 2022-12-23
  • 2021-12-20
  • 2021-10-15
  • 2022-12-23
  • 2021-11-07
相关资源
相似解决方案