You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material 2:实现Mat Tab内滚动及侧边栏顶部按钮固定

实现固定顶部按钮的可滚动Mat Tab侧边栏

我来帮你搞定这个侧边栏的需求!核心思路是把侧边栏拆成固定顶部按钮区和可滚动Tab内容区两部分,用Flex布局控制空间分配,让按钮始终留在视图内,只有Tab内容单独滚动。

步骤1:调整HTML结构

先把侧边栏的元素拆分,明确区分固定区和滚动区:

<mat-sidenav #sidenav mode="side" opened>
  <!-- 固定顶部按钮容器 -->
  <div class="sidenav-header">
    <button mat-button>按钮1</button>
    <button mat-button>按钮2</button>
    <button mat-button>按钮3</button>
  </div>
  <!-- 可滚动的Tab内容容器 -->
  <div class="sidenav-content">
    <mat-tab-group>
      <mat-tab label="标签1">
        <div class="tab-content">
          <!-- 模拟长内容 -->
          <p *ngFor="let item of Array(50).fill(0)">标签1内容行 {{$index + 1}}</p>
        </div>
      </mat-tab>
      <mat-tab label="标签2">
        <div class="tab-content">
          <p *ngFor="let item of Array(50).fill(0)">标签2内容行 {{$index + 1}}</p>
        </div>
      </mat-tab>
    </mat-tab-group>
  </div>
</mat-sidenav>

步骤2:添加CSS样式实现效果

在你的styles.scss或者组件专属样式文件里加上这些样式:

.mat-sidenav {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 让侧边栏占满整个视口高度 */
  overflow: hidden; /* 禁用侧边栏整体滚动,避免全局滚动条 */
}

.sidenav-header {
  flex-shrink: 0; /* 强制固定顶部按钮区高度,不会被内容挤压 */
  padding: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.12); /* 可选:加个分隔线区分按钮区和内容区 */
}

.sidenav-content {
  flex-grow: 1; /* 让内容区自动填充侧边栏剩余空间 */
  overflow-y: auto; /* 只在垂直方向显示滚动条,内容过长时可滚动 */
  padding: 16px;
}

.tab-content {
  padding: 8px; /* 可选:给Tab内容加内边距,避免内容贴边 */
}

关键原理说明

  • Flex布局是核心:侧边栏用flex-direction: column垂直排列子元素,顶部按钮区设置flex-shrink: 0保持固定高度,内容区用flex-grow: 1占满剩余空间。
  • overflow-y: auto只给内容区添加滚动功能,顶部按钮会始终固定在侧边栏顶部,不管内容怎么滚动都不会消失。
  • 侧边栏的overflow: hidden确保整体不会出现多余的滚动条,只有内容区单独滚动。

这样设置后,你打开抽屉就能看到:顶部按钮稳稳停在上方,Tab里的长内容可以独立滚动,完全符合你的需求!

内容的提问来源于stack exchange,提问作者Shadow1349

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:04:31