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

如何使网格布局中主内容div保持16/9宽高比并自适应上下/左右留白?

解决16:9主内容区在窄屏无法上下留白的问题

问题根源是#main的height: 100%强制元素占满网格分配的全部高度,导致aspect-ratio:16/9只能通过调整宽度维持比例(宽屏左右留白),窄屏时无法通过降低高度来适配比例,因此没有上下留白。

修改后的CSS代码

html,
body {
  height: 100%;
}

body {
  margin: 0;
}

#container {
  resize: both;
  max-height: 100%;
  max-width: 100%;
  overflow: auto;
  height: 100%;
  width: 100%;
}

#outer {
  height: 100%;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr auto;
  grid-template-areas: 'main' 'footer'
}

#main {
  grid-area: main;
  border: solid;
  background: blue;
  aspect-ratio: 16/9;
  margin: auto;
  max-height: 100%; /* 替换原有的height:100% */
}

#footer {
  grid-area: footer;
  border: solid;
  background: pink;
  height: 50px;
}

HTML代码保持不变

<div id="container">
  <div id="outer">
    <div id="main">
    </div>
    <div id="footer">
    </div>
  </div>
</div>

效果说明

  • 宽屏状态:主内容区保持16:9比例,超出容器宽度的部分自动左右留白,元素居中显示
  • 窄屏状态:主内容区按16:9比例缩小高度,最大高度不超过网格行的可用空间,超出容器高度的部分自动上下留白,元素垂直水平居中
  • 页脚始终固定在容器底部,保持50px高度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:17:41