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

内层div不遵循外层div的CSS max-height属性问题求助

解决方案:滚动容器自适应内容且不超过最大高度

问题分析

原代码中,.outside仅设置max-height: 500px但未提供明确的高度上下文,导致.inside的height: 100%无法正确计算高度,最终被.content的高度撑开,无法触发滚动。而给.outside设置固定height又会导致内容较短时无法自适应收缩。

可行方案

方案1:Flex布局(推荐)

通过Flex布局给外层容器建立高度上下文,让内层滚动容器自适应空间:

.outside {
    max-height: 500px;
    display: flex;
    flex-direction: column;
    background-color: gray;
}

.inside {
    overflow-y: auto;
    flex: 1;
    background-color: green;
    margin-right: 100px;
}

.content {
    height: 2000px; /* 可替换为任意高度测试 */
    background-color: red;
    margin-right: 100px;
}

关键逻辑:

  • .outside添加display: flex和flex-direction: column,为子元素提供明确的高度参考
  • .inside的flex: 1使其自动填充外层可用空间,同时允许内容较短时跟随外层收缩
  • overflow-y: auto确保内容超出时显示滚动条,未超出时隐藏滚动条

方案2:Grid布局

Grid布局同样能实现自适应效果,代码更简洁:

.outside {
    max-height: 500px;
    display: grid;
    background-color: gray;
}

.inside {
    overflow-y: auto;
    background-color: green;
    margin-right: 100px;
}

.content {
    height: 2000px; /* 可替换为任意高度测试 */
    background-color: red;
    margin-right: 100px;
}

关键逻辑:

  • Grid布局下,子元素默认填充父容器的可用空间,同时父容器会根据子元素的最小高度自动收缩
  • overflow-y: auto实现滚动逻辑

效果验证

  • 当.content高度大于500px时,.inside会被限制在.outside的max-height范围内,内容超出时触发滚动
  • 当.content高度小于500px时,.outside和.inside都会自适应收缩到内容的实际高度,不会出现多余的空白

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:37:29