css实现导航栏折叠吸顶效果

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

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>

在线演示

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值