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

Firefox中图片缩放溢出CSS Grid列的问题解决

解决Firefox中CSS Grid图片容器宽度不自适应问题

我用CSS Grid实现了一个两列布局:

  • 第一列单元格内的图片随单元格高度自动调整宽度,单元格宽度需适配图片尺寸
  • 第二列填充剩余空间

在Chrome中图片会随单元格高度调整尺寸,第一列也能根据图片宽度自动扩展;但在Firefox中图片会溢出容器,第一列单元格宽度无法跟随图片扩展。

问题重现代码

CSS

.container {
  display: grid;
  grid-template-columns: max-content 1fr;
}

.fixed {
  height: 100%;
  border: 1px solid red;
  min-width: max-content;
}

img {
  height: 100%;
  width: auto;
}

.remain {
  height: 100px;
  border: 1px solid blue;
}

input:checked ~ .container > .remain {
  height: 200px;
}

HTML

<!DOCTYPE html>
<html>
  <body>
    <input type="checkbox" />Select to increase .remain height
    <div class="container">
      <div class="fixed"><img src="https://dummyimage.com/24x24/fff700" /></div>
      <div class="remain"></div>
    </div>
  </body>
</html>

解决方案

Firefox在处理Grid布局中max-content列结合height:100%的图片时,存在布局计算逻辑差异,可通过以下方式修复:

给图片所在的.fixed容器添加display: grid(或display: flex),让容器内部建立新的布局上下文,从而让Firefox正确计算图片的宽度,触发外层Grid列的max-content适配:

修改后的CSS

.container {
  display: grid;
  grid-template-columns: max-content 1fr;
}

.fixed {
  height: 100%;
  border: 1px solid red;
  min-width: max-content;
  display: grid; /* 新增:让容器内部建立网格上下文 */
}

img {
  height: 100%;
  width: auto;
}

.remain {
  height: 100px;
  border: 1px solid blue;
}

input:checked ~ .container > .remain {
  height: 200px;
}

原理是:添加display: grid后,.fixed容器会以网格布局包裹图片,Firefox就能正确识别图片的实际宽度,进而让外层Grid的max-content列自动适配这个宽度,避免图片溢出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:05:35