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

实现Flex布局中Sidebar垂直滚动与Toolbar水平滚动

解决方案:实现全屏布局与滚动效果

你的需求很清晰——做一个全屏应用,左侧固定宽度的侧边栏能垂直滚动,右侧自适应区域里,底部固定高度的工具栏支持水平滚动,上方区域自动填充剩余空间。我来帮你调整代码实现这个效果:

核心修改点

  • 给侧边栏添加垂直滚动能力,内容超出高度时自动出现滚动条
  • 给工具栏开启水平滚动,让内部宽表格可以横向滑动
  • 限制页面整体的溢出,确保滚动只在指定容器内触发

修改后的CSS代码

html, body, .my-app { 
  padding: 0; 
  margin: 0; 
  width: 100%; 
  height: 100%; 
  background: red; 
  overflow: hidden; /* 避免页面整体出现滚动条 */
} 

.my-app { 
  display: flex; 
  flex-direction: row; 
} 

.sidebar { 
  background: brown; 
  width: 300px; 
  overflow-y: auto; /* 侧边栏内容超出时垂直滚动 */
  padding: 10px; /* 可选,增加内边距提升视觉体验 */
} 

.map-container { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  overflow: hidden; /* 防止子元素溢出容器 */
} 

.map { 
  background: blue; 
  flex: 1; 
  padding: 10px;
  overflow: auto; /* 可选,如果map内部内容也会溢出的话开启 */
} 

.toolbar { 
  height: 300px; 
  background: green; 
  overflow-x: auto; /* 工具栏内容超出时水平滚动 */
  overflow-y: hidden; /* 禁止工具栏垂直滚动 */
  padding: 10px;
}

.large-table {
  white-space: nowrap; /* 确保表格内容不换行,触发水平滚动 */
}

修改后的HTML代码

<div class="my-app">
  <div class="sidebar">
    <p> Sidebar fixed width of 300px; </p>
    <!-- 增加测试内容,验证垂直滚动效果 -->
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
    <p>测试内容</p>
  </div>
  <div class="map-container">
    <div class="map">
      <p> Map should grow to fill available space horizontally and vertically </p>
    </div>
    <div class="toolbar">
      <table class="large-table">
        <tr>
          <td>Content should scroll and be 300px</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
          <td>Content</td>
        </tr>
      </table>
    </div>
  </div>
</div>

关键效果说明

  1. 页面整体溢出控制:给html, body, .my-app添加overflow: hidden,确保页面不会因为内部元素溢出而出现全局滚动条,所有滚动都限制在指定容器内。
  2. 侧边栏垂直滚动:.sidebar设置overflow-y: auto,当内容高度超过侧边栏的可用高度时,自动显示垂直滚动条,不影响页面其他区域。
  3. 工具栏水平滚动:.toolbar开启overflow-x: auto并关闭垂直滚动,同时给表格添加white-space: nowrap,保证表格内容不自动换行,触发横向滚动。
  4. 自适应区域填充:map-container用flex垂直布局,.map通过flex: 1自动填充工具栏以外的剩余空间,完美适配不同屏幕尺寸。

这样调整后,就能完全实现你想要的布局和滚动效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:52:41