CSS 粘性属性在此演示中不起作用

CSS Sticky attribute is not working in this demo

当我编码时,我发现 position : sticky 不起作用。 这是一个简单的演示。

<!DOCTYPE html>
<html>
  <head> </head>

  <body style='height: 2000px;'>
    <div>
      <div>
        <div>
          <div style="height: 300px">
            <div
              style="
                top: 87px;
                height: 40px;
                background: blue;
                margin-top: 10px;
                position: sticky;
                position: -webkit-sticky;
              "
            ></div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

这个例子没有达到我想要的效果。是我哪里有问题吗 ?

Sticky 位置与最近的父级相关 - 在您的示例中,高度为 300px 的元素可以正常工作:)

它粘到300px的高度,这是粘延伸到它的容器元素的行为,之后它将成为一个正常的默认定位元素。

添加了一个 background-color 用于显示您的元素作为 sticky

工作的视觉效果

<!DOCTYPE html>
<html>

<head> </head>

<body style='height: 2000px;'>
  <div>
    <div>
      <div>
        <div style="height: 300px;background-color:rgba(126, 125, 125, 0.5);">
          <div style="
                top: 87px;
                height: 40px;
                background: blue;
                margin-top: 10px;
                position: sticky;
                position: -webkit-sticky;
              "></div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>