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

被折叠的 条评论
为什么被折叠?



