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

两个各占50vh的div页面布局resize时元素重叠问题求解决方案

解决办法

问题根源

你设置的两个div各占50vh,但中间还有独立的<button>元素,总内容高度等于100vh + button高度,已经超出视口高度。同时div用了固定的height:50vh,当视口高度缩小到不足以容纳div内部的<h1>、输入框时,内容会溢出并和其他元素重叠。

可行方案

方案1:改用min-height并开启页面滚动

把div的固定高度改成最小高度,同时清除body默认边距、允许垂直滚动,这样内容总高度超过视口时会自动出现滚动条,元素不会重叠:

#top {
  background-color: red;
}

#bottom {
  background-color: blue;
}

div {
  min-height: 50vh; /* 改为最小高度,让内容能撑开元素 */
}

body {
  margin: 0; /* 清除body默认外边距,避免额外高度 */
  overflow-y: auto; /* 允许垂直方向滚动 */
}

方案2:用flex布局统一管理容器

把所有元素放进一个容器,用flex垂直布局让容器占满视口,元素自动分配空间,超出时滚动:

<div class="container">
  <div id='top'>
    <h1>Test</h1>
    <input id='testInputOne' type='text'>
  </div>
  <button id='testButton' type='button'>Test</button>
  <div id='bottom'>
    <input id='testInputTwo' type='text'>
    <h1>Test</h1>
  </div>
</div>
.container {
  min-height: 100vh; /* 容器最小占满视口 */
  display: flex;
  flex-direction: column;
}

#top {
  background-color: red;
  flex: 1;
  min-height: 50vh;
}

#bottom {
  background-color: blue;
  flex: 1;
  min-height: 50vh;
}

body {
  margin: 0;
  overflow-y: auto;
}

方案3:清除默认样式修正高度计算

浏览器默认会给body、h1等元素加margin,额外增加了内容高度,先清除这些默认样式:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box; /* 确保内边距、边框不额外增加元素高度 */
}

#top {
  background-color: red;
  height: 50vh;
}

#bottom {
  background-color: blue;
  height: 50vh;
}

body {
  overflow-y: auto;
}

处理后两个div各占50vh,中间的button会被挤到视口外,页面可滚动查看,不会出现重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:35:25