You need to enable JavaScript to run this app. CSS Flex布局如何实现侧边栏内的div内容可滚动?
优惠活动
大模型
产品
解决方案
定价
更多

CSS Flex布局如何实现侧边栏内的div内容可滚动?

解决方案

问题根源是 Flex 纵向布局的子元素默认 min-height: auto,会优先适配内容高度,即使父容器设置了溢出隐藏也不会被压缩,因此会出现超出容器的问题。你只需要调整部分 CSS 属性即可实现需求:

修改后的完整CSS代码

.drawer {
    flex: 0 0 240px;
    height: 100%;
    overflow-y: hidden;
    padding: 10px 0;
}

.drawerContainer {
    height: inherit;
    overflow: hidden;
    padding-bottom: 10px;
    padding-top: 10px;
}

.sideboxWrapper {
    display: flex;
    flex-direction: column;
    height: inherit;
    overflow: hidden;
    justify-content: flex-start;
}

.sidebox {
    margin: 10px;
    padding: 0px;
    /* 核心设置:不主动拉伸、允许收缩、基础高度为内容自身高度 */
    flex: 0 1 auto;
    /* 覆盖默认min-height:auto,允许盒子被压缩到小于内容高度 */
    min-height: 0;
    display: flex;
    flex-direction: column;
}

.boxContent {
    /* 占满sidebox减去header后的全部剩余空间 */
    flex: 1 1 auto;
    min-height: 0;
    overflow-y: auto;
}

效果验证

  • 内容总高度小于侧边栏高度:两个盒子仅占用自身内容所需高度,侧边栏剩余空间留空,符合需求
  • 内容总高度超出侧边栏高度:两个盒子自动收缩适配可用空间,boxheader始终完整展示,内容超出的盒子的boxContent区域自动出现滚动条,可滚动查看全部列表项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:54:04