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

Grid布局下<figure>内<img>垂直溢出:如何适配剩余空间?

Grid布局下图片垂直溢出与纵向布局失效的问题解决

问题描述

将<figure>设为Grid布局,内部包含<img>和<figcaption>,期望实现:

  • 图片占据标题剩余垂直空间,不溢出、不扭曲尺寸
  • 图片尺寸小于屏幕时保持原大小,大于屏幕时自适应缩放

但实际运行存在两个问题:

  1. 大尺寸图片会溢出Grid容器高度
  2. 使用grid-template-columns做横向布局正常,grid-template-rows纵向布局却失效

问题代码

CSS代码

.lightbox {
  width: 100vw;
  height: 100vh;
}

.lightbox figure {
  display: grid;
  max-height: 100%;
  grid-template-rows: 1fr min-content;
}

.lightbox figure img {
  min-height: 100%;
  min-width: 100%;
  object-fit: cover;
  vertical-align: bottom;
}

.lightbox figure figcaption {
  text-align: center;
}

HTML代码

<div class="lightbox">
  <figure>
    <div>
      <img src="https://placehold.co/6000x4000">
    </div>
    <figcaption>This is 1 caption for this image. Words Words Words. And some more words. We need to fill up some space here. Wahey.</figcaption>
  </figure>
</div>

问题原因分析

  1. Grid容器高度无明确约束:.lightbox figure仅设置max-height:100%,没有强制高度限制,当内部大尺寸图片撑大容器时,会突破父容器的100vh限制,导致溢出。max-height仅约束最大高度,不会主动限制容器随内容扩张。
  2. 图片样式错误触发溢出:min-height:100%强制图片至少占满Grid行高度,但图片原始宽高比可能导致其在满足宽度时高度超出行高,object-fit:cover仅裁剪显示内容,不会压缩图片的实际占位高度,最终撑破Grid行。
  3. 嵌套div未被约束:<img>外层的<div>是Grid的直接子元素,但未设置高度约束,导致图片的样式无法直接作用于Grid行,进而让图片不受限地撑开容器。

修正方案

修复后的CSS代码

.lightbox {
  width: 100vw;
  height: 100vh;
  overflow: hidden; /* 阻止内容溢出屏幕 */
}

.lightbox figure {
  display: grid;
  height: 100%; /* 明确Grid容器高度,继承父容器100vh */
  grid-template-rows: 1fr min-content;
  margin: 0; /* 清除figure默认margin,避免占用额外空间 */
}

.lightbox figure > div {
  height: 100%; /* 让Grid行内的div占满行高 */
  overflow: hidden; /* 限制图片的占位范围 */
}

.lightbox figure img {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保证图片完整显示,不裁剪;需求裁剪可换为cover */
  object-position: center; /* 图片居中对齐 */
}

.lightbox figure figcaption {
  text-align: center;
  padding: 8px; /* 给标题加内边距,提升排版体验 */
}

修复后的HTML代码(结构无需修改)

<div class="lightbox">
  <figure>
    <div>
      <img src="https://placehold.co/6000x4000">
    </div>
    <figcaption>This is 1 caption for this image. Words Words Words. And some more words. We need to fill up some space here. Wahey.</figcaption>
  </figure>
</div>

关键修复点

  • 给Grid容器设置height:100%,让1fr行能准确计算标题以外的剩余空间
  • 给图片外层div添加height:100%和overflow:hidden,约束图片的占位范围
  • 将图片的min-height/min-width改为width:100%;height:100%,配合object-fit实现自适应缩放,保证图片不扭曲、不溢出
  • 清除<figure>默认margin,避免额外高度占用图片空间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:58:26