flex布局实现左侧固定宽度,右侧自适应

407 阅读2分钟

一、核心实现思路

使用Flexbox实现该布局的关键在于:

  1. 左侧元素:通过 flex-shrink: 0 禁止收缩,并设置固定宽度(如 width: 200px)。
  2. 右侧元素:使用 flex: 1flex-grow: 1 让其自动填充剩余空间。

二、基础实现代码

<div class="container">
  <div class="sidebar">固定宽度</div>
  <div class="main-content">自适应内容</div>
</div>

<style>
.container {
  display: flex;
}
.sidebar {
  flex-shrink: 0;  /* 禁止收缩 */
  width: 200px;     /* 固定宽度 */
}
.main-content {
  flex-grow: 1;     /* 自动填充剩余空间 */
}
</style>

三、进阶实现(响应式 + 优化)

  1. 响应式设计:在小屏幕上转为垂直布局。
  2. 间距控制:使用 gapmargin 控制元素间距。
  3. 完整代码
    <div class="container">
      <div class="sidebar">固定宽度</div>
      <div class="main-content">自适应内容</div>
    </div>
    
    <style>
    .container {
      display: flex;
      gap: 16px; /* 元素间距 */
    }
    
    .sidebar {
      flex-shrink: 0;
      width: 200px;
      background: #f0f0f0;
    }
    
    .main-content {
      flex: 1; /* 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: 0; */
      background: #e0e0e0;
    }
    
    /* 响应式:小屏幕下转为垂直布局 */
    @media (max-width: 768px) {
      .container {
        flex-direction: column;
      }
      .sidebar {
        width: 100%; /* 垂直布局时宽度撑满 */
      }
    }
    </style>
    

四、变体实现(动态切换侧边栏)

通过 JavaScript 动态调整侧边栏宽度,实现展开/收起效果:

<button id="toggle-sidebar">切换侧边栏</button>
<div class="container">
  <div id="sidebar" class="sidebar">固定宽度</div>
  <div class="main-content">自适应内容</div>
</div>

<style>
.sidebar {
  flex-shrink: 0;
  width: 200px;
  transition: width 0.3s;
}
.sidebar.collapsed {
  width: 60px; /* 收起后的宽度 */
}
</style>

<script>
document.getElementById('toggle-sidebar').addEventListener('click', () => {
  const sidebar = document.getElementById('sidebar');
  sidebar.classList.toggle('collapsed');
});
</script>

五、问题

1. 问:为什么右侧元素设置 flex: 1 就能自适应?


  • flex: 1flex-grow: 1flex-shrink: 1flex-basis: 0 的简写。
    • flex-grow: 1 让元素在剩余空间中按比例扩张。
    • flex-basis: 0 使元素初始大小为 0,所有空间由 flex-grow 分配。

2. 问:如果左侧固定元素内容超出宽度会怎样?如何处理?


  • 默认会溢出容器。可通过以下方式处理:
    .sidebar {
      overflow: auto; /* 超出部分显示滚动条 */
      white-space: nowrap; /* 文本不换行 */
      text-overflow: ellipsis; /* 超出部分显示省略号 */
    }
    

3. 问:如何实现左右两侧固定宽度,中间自适应?

  • .container {
      display: flex;
    }
    .left, .right {
      flex-shrink: 0;
      width: 200px;
    }
    .middle {
      flex: 1;
    }