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

CSS Grid gap破坏布局:如何实现无溢出的计算器网格居中

解决CSS Grid gap溢出及网格元素居中问题

核心问题分析

设置gap: 1em后出现溢出,是因为你之前用grid-template-rows: 25%时,25%的行高基于容器高度计算,但gap会额外占用空间——4行的话总垂直gap是3em,25%×4 + 3em的总高度会超过容器100%的高度,最终导致溢出。


解决方案

1. 修复溢出:改用自适应轨道尺寸

放弃固定百分比,用以下两种方式之一解决:

方式一:使用fr单位(推荐)

fr是Grid的分数单位,会自动扣除gap占用的空间后,将剩余空间平均分配给各个轨道,完全避免溢出:

.calculator__body {
  display: grid;
  gap: 1em;
  /* 4行4列,每行/列平分剩余空间 */
  grid-template-rows: repeat(4, 1fr);
  grid-template-columns: repeat(4, 1fr);
  height: 100%; /* 确保容器占满父元素高度 */
  box-sizing: border-box;
}
方式二:用calc()精确计算轨道尺寸

如果必须保留百分比逻辑,手动扣除gap的总占用:

.calculator__body {
  display: grid;
  gap: 1em;
  /* 4行有3个垂直gap,总gap高度是3em,每行高度 = (容器总高 - 总gap)/4 */
  grid-template-rows: repeat(4, calc((100% - 3em)/4));
  grid-template-columns: repeat(4, calc((100% - 3em)/4));
  height: 100%;
  box-sizing: border-box;
}

2. 实现网格元素居中

直接在网格容器上设置place-items: center,一键实现子元素水平+垂直居中:

.calculator__body {
  /* 其他Grid属性... */
  place-items: center;
}

如果需要分开控制水平/垂直方向,也可以单独设置:

.calculator__body {
  justify-items: center; /* 水平居中 */
  align-items: center;   /* 垂直居中 */
}

完整示例代码

/* 计算器容器 */
.calculator {
  width: 320px;
  height: 450px;
  border: 2px solid #222;
  border-radius: 12px;
  overflow: hidden; /* 防止意外溢出 */
}

.calculator__body {
  display: grid;
  gap: 1em;
  grid-template-rows: repeat(4, 1fr);
  grid-template-columns: repeat(4, 1fr);
  place-items: center;
  height: 100%;
  padding: 1em;
  box-sizing: border-box;
}

.calculator__btn {
  width: 90%;
  height: 90%;
  font-size: 1.2rem;
  border: none;
  border-radius: 8px;
  background-color: #e0e0e0;
  cursor: pointer;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:55:31