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

如何解决CSS中窗口缩放时元素超出屏幕的问题?

问题解决方案

核心问题分析

你的section2盒子超出屏幕,是因为固定高度90vh加上上下各3%的margin,总高度会超过视口高度,再加上flex容器未做视口适配,导致内容溢出。


解决方法一:计算元素高度

修改CSS,通过calc()让section2的高度加上margin刚好等于视口高度,同时重置默认样式避免偏差:

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  background-image: url('bg.png');
  background-size: contain;
}

.container {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
}

.section1,
.section2 {
  flex-basis: 50%;
  flex-grow: 0;
  flex-shrink: 0;
}

.section2 {
  background-color: blanchedalmond;
  z-index: 1;
  position: relative;
  margin-top: 3%;
  margin-bottom: 3%;
  margin-right: 3%;
  height: calc(100vh - 6%); /* 视口高度减去上下margin总和 */
}

解决方法二:通过容器padding控制空间

把section2的上下margin换成容器的padding,让section2占满容器高度,逻辑更简洁:

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  background-image: url('bg.png');
  background-size: contain;
}

.container {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
  padding: 3% 0; /* 预留上下空间 */
  box-sizing: border-box;
}

.section1,
.section2 {
  flex-basis: 50%;
  flex-grow: 0;
  flex-shrink: 0;
}

.section2 {
  background-color: blanchedalmond;
  z-index: 1;
  position: relative;
  margin-right: 3%;
  height: 100%;
}

关键修改点说明

  1. 重置html和body的默认margin/padding,消除浏览器默认样式的干扰
  2. 给container设置min-height:100vh,确保容器覆盖整个视口高度
  3. 取消flex-grow:1,改用flex-basis:50%+flex-shrink:0,保证左右区块各占50%宽度,避免宽度溢出
  4. 两种方法都确保section2的总占用高度(元素高度+外边距/容器padding)不超过视口高度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:35:04