You need to enable JavaScript to run this app. 如何实现全屏幕下可变高度div内部内容的垂直居中
优惠活动
大模型
产品
解决方案
定价
更多

如何实现全屏幕下可变高度div内部内容的垂直居中

问题根因

  1. 页脚设置了position: absolute脱离文档流,中间内容区域无法感知页脚高度,不同屏幕下会出现多余空白
  2. 外层容器没有设置占满视口高度的弹性布局,md-sec-2的margin: auto缺少生效的布局上下文
  3. 中间内容区域没有设置弹性占比,无法自动填充header和footer之间的剩余空间

具体修改方案

1. 新增全局样式重置+外层弹性布局配置

/* 新增全局重置,清除默认边距避免布局偏移 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 调整page-section属性,设置占满视口的纵向弹性布局 */
.page-section {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    /* 原有属性保留 */
    background-color: #035DA9;
    font-family: "Mulish", sans-serif;
}

/* 给最外层包裹div设置弹性属性,占满body剩余高度 */
.page-section > div:first-child {
  display: flex;
  flex-direction: column;
  flex: 1;
}

2. 调整middle-section样式

.middle-section{
    width: 100%; /* 替换原有的100vw,避免滚动条导致横向溢出 */
    flex: 1; /* 自动填充header和footer之间的所有剩余空间 */
    display: flex;
    flex-direction: column;
    /* 删除原有的margin-left: -8px */
}

3. 调整md-sec-2样式实现内部内容垂直居中

.md-sec-2{
    color: white;
    flex: 1; /* 占满middle-section内部md-sec-1之外的剩余空间 */
    display: flex;
    flex-direction: column;
    justify-content: center; /* 内部内容垂直居中 */
    align-items: center; /* 内部内容水平居中 */
    /* 删除原有的margin-top: auto、margin-bottom: auto */
}

4. 修正footer的定位属性,回归正常文档流

.footer-section {
    background-color: white;
    height: auto;
    width: 100%; /* 替换原有的100vw */
    display: flex;
    /* 删除原有的position: absolute、bottom: 0px、margin-left: 0px */
}

可选优化项

  • 可将header-section设置justify-content: space-between,删掉navbarLinks的绝对定位,避免小屏导航错位
  • 移动端媒体查询里的update-image属性display: inherit可改为display: flex; flex-direction: column,布局更稳定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:45:01