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

如何用CSS垂直堆叠DIV?解决容器滚动条与面板高度异常问题

垂直堆叠固定高度面板的问题修复

问题根源

  1. 高度继承失效:外层容器设置了height:100%,但如果父元素(html/body)没有明确高度,这个百分比会被解析为“内容自适应高度”,导致容器被内部内容撑开,出现滚动条。
  2. 默认样式干扰:浏览器给body、h3、p等元素自带margin/padding,这些额外间距会让面板总高度超过容器的50%+50%设定。
  3. 盒模型未重置:默认盒模型下,元素的padding、border会额外增加高度,导致两个面板的实际总高度超出容器。

修正代码

CSS

/* 确保外层容器的height:100%能正确继承高度 */
html, body {
  height: 100%;
  margin: 0; /* 清除body默认margin,避免布局偏移 */
}

#contains_upper_and_lower_panes {
  overflow: hidden; /* 只需写一次即可,覆盖所有方向 */
  background: white;
  margin-top: -113px;
  height: 100%;
  width: 45rem;
  box-sizing: border-box; /* 让padding/border计入设定高度 */
}

.halfPane {
  width: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  height: 50%;
  box-sizing: border-box;
}

/* 可选:优化内部元素排版,清除默认margin避免额外高度 */
.halfPane h3, .halfPane p {
  margin: 0;
  padding: 0.5rem; /* 替代默认margin,提升排版美观度 */
}

HTML

<div id="contains_upper_and_lower_panes">
  <div id="upper_pane" class="halfPane">
    <h3>top</h3>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <!-- 可添加更多段落测试滚动效果 -->
  </div>

  <div id="lower_pane" class="halfPane">
    <h3>bottom</h3>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <p>paragraph</p>
    <!-- 可添加更多段落测试滚动效果 -->
  </div>
</div>

效果说明

  • 外层容器始终保持设定高度,不会出现滚动条。
  • 两个面板固定占容器的50%高度,内容过多时仅面板自身显示垂直滚动条。
  • 盒模型重置后,即使给面板添加padding或border,也不会打破高度比例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:50:25