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

如何让Grid容器内的4个盒子居中且等比例自适应,匹配容器尺寸?

问题解决:Grid容器内盒子居中与自适应同步缩放调整

核心问题分析

  1. 容器通过:after伪元素实现正方形的方式干扰了Grid布局,导致容器尺寸异常
  2. grid-area属性值错误添加引号,网格区域无法正确匹配
  3. 盒子的:after伪元素额外占用空间,破坏了容器与盒子的同步缩放关系
  4. 网格行列使用百分比单位,无法灵活适配容器内边距和间距需求

修改后的完整代码

CSS

* {
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  width: 50%;
  aspect-ratio: 1/1; /* 简洁实现正方形容器,替代伪元素方案 */
  background: Crimson;
  margin: 10vh auto; /* 用vh替代百分比,居中更稳定 */
  padding: 8px; /* 容器与盒子间的内边距 */
  gap: 8px; /* 盒子之间的间距 */
  grid-template-areas: 
    "first second" 
    "third forth";
  grid-template-columns: 1fr 1fr; /* 用fr均分剩余空间 */
  grid-template-rows: 1fr 1fr;
  border-radius: 5px;
}

.box {
  box-shadow: 5px 5px 4px #a11d33;
  background: #ED365B;
  border-radius: 5px;
  color: white;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Helvetica;
  transition-duration: 0.4s;
  cursor: pointer;
}

.box:hover {
  background: #ff4d6d;
  color: #800f2f;
}

/* 修正grid-area写法,去掉引号 */
.first {
  grid-area: first;
}

.second {
  grid-area: second;
}

.third {
  grid-area: third;
}

.forth {
  grid-area: forth;
}

HTML

<!DOCTYPE html>
<html>

<head>
  <title>Index</title>
  <link rel="stylesheet" href="myCSS.css">
</head>

<body>
  <div class="container">
    <div class="box first">First</div>
    <div class="box second">Second</div>
    <div class="box third">Third</div>
    <div class="box forth">Forth</div>
  </div>
</body>

</html>

关键修改说明

  • 正方形容器实现:用aspect-ratio: 1/1替代:after伪元素方案,避免干扰Grid布局,同时保证容器始终为正方形,自适应缩放更稳定
  • 网格空间分配:使用1fr单位让行列均分容器空间,配合padding和gap精准控制容器内边距与盒子间距
  • 居中优化:容器用margin: 10vh auto实现垂直水平居中,vh单位比百分比更适配视口缩放
  • Grid区域修正:移除grid-area值的引号,确保网格区域正确匹配,盒子能按预期布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:57:40