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

垂直布局下高度未知Div搭配可滚动长内容Div的实现方案

解决方案:用Flexbox轻松实现自适应布局

完全可以用Flexbox实现你要的效果,而且不需要提前设置#first的高度,它会自动根据内容调整,同时让#second占据剩余空间并支持滚动。

修改后的完整代码

HTML部分(无需改动)

<div id="container">
 <div id="first">
 Some random stuff (but should be small)<br>
 Like few lines<br>
 No more
 </div>
 <div id="second">
 <div id="content">
 This can be very very<br>
 very very<br>
 very long
 </div>
 </div>
</div>

CSS部分(关键修改标注)

/* 先给根元素设置高度,让#container能拿到100%可用高度 */
html, body {
 height: 100%;
 margin: 0;
 padding: 0;
}

#container {
 height: 100%;
 width: 90%;
 margin: auto;
 overflow: hidden;
 display: flex;
 flex-direction: column;
 border: solid black 1px;
}

#first {
 width: 90%;
 margin: auto;
 background-color: cyan;
 /* 不需要设置高度,Flex会自动适配内容 */
}

#second {
 width: 90%;
 margin: auto;
 background-color: pink;
 /* 关键1:让这个div填充容器剩余的所有空间 */
 flex-grow: 1;
 /* 关键2:内容超出时自动显示滚动条 */
 overflow: auto;
 /* 可选:防止margin导致布局溢出,统一盒模型 */
 box-sizing: border-box;
}

#content {
 width: 100%;
 height: 1000px;
}

核心原理说明

  1. 容器基础布局:#container通过display: flex + flex-direction: column实现垂直排列,配合height:100%(依赖html/body的高度设置)占据全部可用高度。
  2. #first自适应显示:Flex布局中,未设置flex-grow的元素会自动收缩到内容所需的最小高度,所以#first始终完整展示所有内容,不会被压缩或截断。
  3. #second占满剩余空间并滚动:flex-grow:1让#second自动填充容器中#first之外的所有剩余空间;overflow:auto则在内容高度超过这个空间时自动显示滚动条,内容较短时保持正常显示。

这样不管#first的内容是1行还是多行,它都会完整展示,#second则会自适应剩余高度,内容过长时可以滚动查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:22:27