position:sticky粘性/悬浮定位

文章介绍了CSS中的sticky定位,它是static和fixed定位的结合体。当元素在父元素滚动过程中达到指定位置(如top:40px),它会像fixed一样固定在那个位置。sticky定位只能在overflow属性设置的父元素中使用,且需指定top、bottom、left或right之一。文章提供了一个Vue2的例子,展示如何在滚动过程中使元素悬浮在特定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、通俗易懂

2、sticky介绍

3、举例(Vue2为例)


1、通俗易懂

  • position:sticky可以简单理解为是static和fixed的结合;
  • 可理解为在父元素滑动过程中,子元素距离其父元素的距离达到 sticky 粘性定位的要求时(如top:40px);position:sticky这时的效果相当于fixed定位,固定到适当位置。

2、sticky介绍

  • sticky只能在最接近的父元素为overflow中使用;
  • 至少规定top, left ,right, bottom中的一种, 否则stikcy定位不生效,最终效果类似于relative;
  • 假设定义了top(bottom)属性. 那么父元素height不能低于top(bottom)的值;
  • 使用前请检查兼容性

3、举例(Vue2为例)

如上图二:滑动后,红色div脱离原本的蓝色框所在文档流,最终悬浮在父容器top:40px处

 

<template>
  <div class="box">
    <div class="box-scroll">
      <div v-for="(item, index) in 10" :key="index">{{ index + 1 }}</div>
      <div class="box-scroll-sticky">我要悬浮在40px处</div>
      <div v-for="(item, index) in 100" :key="index">{{ index + 1 }}</div>
    </div>
  </div>
</template>
<script>
export default {};
</script>
<style lang="scss" scoped>
.box {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  &-scroll {
    height: 400px;
    width: 400px;
    background: #eee;
    overflow: auto; //父元素必须是scroll
    display: flex;
    flex-direction: column;
    position: relative;
    > div {
      width: 100%;
      height: 40px;
      border-bottom: 2px solid #fff;
    }
    &-sticky {
      position: sticky;
      top: 40px; //至少设置一个
      background: red;
      color: #fff;
    }
  }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值