position:sticky

position:sticky,粘性定位,在表现方式上可以理解为relative和fixed定位的结合,当元素在屏幕内,变现为relative;当元素要滚出屏幕时,表现为fixed

使用sticky完成的一个有层次的滚动交互。

HTML结构:

 <div class="containner">
      <div class="item">
        <div class="title">测试标题1</div>
        <div class="content">测试内容测试内容测试内容测试内容测试内容测试内容1</div>
        <div class="comment">测试评论测试评论测试评论测试评论测试评论测试评论测试评论1</div>
      </div>
      <div class="item">
        <div class="title">测试标题2</div>
        <div class="content">测试内容测试内容测试内容测试内容测试内容测试内容2</div>
        <div class="comment">测试评论测试评论测试评论测试评论测试评论测试评论测试评论2</div>
      </div>
      <div class="item">
        <div class="title">测试标题3</div>
        <div class="content">测试内容测试内容测试内容测试内容测试内容测试内容3</div>
        <div class="comment">测试评论测试评论测试评论测试评论测试评论测试评论测试评论3</div>
      </div>
    </div>

css部分:

.containner {
        width: 600px;
        height: 800px;
        overflow-y: auto;
        outline: 1px solid red;
        margin: 0 auto;
      }

      .item {
        width: 100%;
        height: 600px;
        outline: 1px solid red;
        text-align: center;
        /* overflow: auto; */
      }

      .title {
        height: 40px;
        line-height: 40px;
        background: red;
        color: white;
        position: sticky;
        top: 0;
      }

      .content {
        height: 460px;
        line-height: 460px;
        background: black;
        color: white;
      }

      .comment {
        height: 100px;
        line-height: 100px;
        background: green;
        color: white;
        position: sticky;
        bottom: 50vh;
        z-index: -1;
      }

页面效果

image.png
image.png

sticky注意点

1 设置了sticky的元素的父元素overflow不能有visible以外的设置,否则没有沾滞效果
2 设置为sticky的元素的父元素的高度不能和sticky元素的高度一样,否则没有沾滞效果
3 同一个父元素中的sticky元素独立偏移,可能会重叠;不同父元素中的sticky元素会挤开原来的元素,形成依次占位的效果

sticky粘性定位的计算规则

流盒

距离sticky元素最近的可滚动的元素的尺寸盒子,如果有left,top等则是可滚动的元素的尺寸盒子像右或者是向下偏移left,top值。

粘性约束矩形

sticky元素的父元素和流盒的重叠区域

同position:sticky一同使用的left,right,top,bottom代表的意思

例如:top:20px;流盒顶部距离最近的可滚动父元素的顶部为20px

什么时候开始有沾滞效果

当粘性约束矩形顶部距离流盒顶部距离为0的时候开始有沾滞效果

什么时候沾滞效果消失

当粘性约束矩形底部距离sticky元素的距离为0的时候沾滞效果消失

验证sticky粘性定位的计算规则的小demo

https://www.zhangxinxu.com/st...


慢慢领会路上风景
13 声望1 粉丝

千里之行,始于足下