1.效果需求
一个侧边栏,有一级标题和二级标题,需要在向下滚动的过程中一级标题逐步到达顶部吸顶折叠收起,向上滚动的过程中又逐步离开顶部展开。

2.css基本示例
本来打算采用Js的技术解决,但发现有点麻烦,于是查到了可以使用 position: sticky粘性定位属性实现。
粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值前为相对定位,之后为固定定位
//css
.container{
width:200px;
height: 300px;
overflow-y:auto;
border:1px solid#dedede;
position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
.egDiv{
position: -webkit-sticky;
position: sticky;
top:0px;
height:25px;
background:grey;
// margin-bottom:200px;
color:#fff;
}
.content{
height:400px;
border-bottom:1px solid#dedede;
}
//html
<div class="egDiv">1</div>
<div class="content"></div>
<div class="egDiv">2</div>
<div class="content"></div>
<div class="egDiv">3</div>
<div class="content"></div>
<div class="egDiv">4</div>
<div class="content"></div>
<div class="egDiv">5</div>
<div class="content"></div>
3.实现
导航栏折叠吸顶效果实现
//css
.container{
width:400px;
height: 300px;
overflow-y: auto;
border:1px solid#dedede;
position: absolute;
margin: auto;
top:0;
left: 0;
right: 0;
bottom: 0;
}
.nav-title{
height: 40px;
text-align: center;
line-height: 40px;
color:#fff;
position: -webkit-sticky;
position: sticky;
text-align: center;
z-index: 2;
}
.nav-content{
color:#fff;
text-align: center;
z-index: 1;
height: 400px;
}
.title1{
background:red;
top:0;
}
.title2{
background:blue;
top:40px;
}
.title3{
background:green;
top:80px;
}
.title4{
background:purple;
z-index: 5;
top:120px;
}
//html
<div class="container">
<div class="nav-title title1">标题一</div>
<div class="nav-content content1">标题内容一</div>
<div class="nav-title title2">标题二</div>
<div class="nav-content content2">标题内容二</div>
<div class="nav-title title3">标题三</div>
<div class="nav-content content3">标题内容三</div>
<div class="nav-title title4">标题四</div>
<div class="nav-content content4">标题内容四</div>
</div>
CSS实现导航栏折叠吸顶效果

本文介绍了如何使用CSS实现导航栏在页面滚动时的折叠吸顶效果。通过利用粘性定位属性,使得侧边栏的一级标题在滚动过程中能实现吸顶折叠,向上滚动时则展开。
1115

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



