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

Angular 12项目如何让页面内容展示在固定侧边栏右侧且左右间距均匀

解决方案

首先调整app.component.html的结构,在侧边栏下方新增内容容器包裹路由出口:

<nav class="navbar navbar-expand d-flex flex-column align-item-start sidebar">
    <a class="navbar-brand mt-2">
      <img  [src]="IconUrl" height="50" width="120">
    </a>
    <ul class="navbar-nav d-flex flex-column mt-2 w-100">
        <li class="nav-item w-100">
            <a class="nav-link text-light pl-4" [routerLink]="['home']" 
             routerLinkActive="active"><i class="fa fa-home me-2"></i>Home</a>
        </li>
    </ul>
</nav>
<!-- 新增内容容器 -->
<div class="main-content">
  <router-outlet></router-outlet>
</div>

然后修改styles.scss样式:

// 全局重置默认边距,避免浏览器默认样式干扰
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.sidebar {
  width: 20%;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background-color: $purple;
  transition: all 0.4s ease;
  color: $white;
  z-index: 100; // 保证侧边栏层级高于内容,不会被覆盖
}

.main-content {
  width: 80%;
  margin-left: 20%; // 避开侧边栏宽度,防止内容被遮挡
  min-height: 100vh;
}

// 所有路由页面的内容外层统一加这个类,即可实现左右边距相等
.page-container {
  max-width: 1200px; // 可根据需求调整内容最大宽度
  margin: 0 auto;
  padding: 2rem 1.5rem; // 可自定义上下内边距
}

最后在首页组件的内容外层套上page-container类即可:

<!-- home.component.html 示例 -->
<div class="page-container">
  <!-- 首页所有内容写在这里 -->
</div>

实现逻辑

  • fixed定位的侧边栏脱离了正常文档流,给内容容器设置margin-left: 20%可以刚好把内容整体推到侧边栏右侧,不会出现重叠
  • 内容容器本身占满剩余80%的屏幕宽度,内部内容通过margin: 0 auto实现水平居中,自然满足内容左侧到侧边栏、右侧到屏幕边缘的距离相等的要求
  • 后续如果需要调整侧边栏宽度,只需要同步修改.sidebar的width和.main-content的width、margin-left即可,无需修改页面级样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:36:02