css grid布局实现九宫格怎么办_通过repeat和fr单位快速布局

用CSS Grid实现九宫格只需设置display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr);,配合gap、justify-items和align-items可轻松实现等分、间隙与内容居中,子项设aspect-ratio: 1可确保正方形。

用 CSS Grid 实现九宫格非常简单,核心就是 grid-template-columnsgrid-template-rows 配合 repeat()fr 单位。

用 repeat(3, 1fr) 一次性定义三行三列

九宫格本质是 3×3 的等分网格。直接写:

display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);

这样就创建了 3 列等宽、3 行等高的网格容器,9 个子元素会自动按源顺序填满格子(从左到右、从上到下)。

保证每个格子是正方形(可选但常用)

如果希望九宫格每个单元是正方形(比如头像墙、图标菜单),可以结合 aspect-ratio: 1 或利用 padding-bottom 技巧,更推荐现代写法:

  • 给每个子项设置 aspect-ratio: 1,并设 width: 100%,它会自动保持正方形
  • 或者统一控制容器:用 grid-auto-rows: 1fr + 子项 height: 0; padding-bottom: 33.33%(需配合 position: relative 和绝对定位内容)

加间隙用 gap,别用 margin

想让格子之间有空隙,直接用 gap: 8px(同时作用于行和列),简洁又可靠:

  • gap: 8px 等价于 row-gap: 8px; column-gap: 8px
  • 避免对子元素设 margin,容易破坏对齐,也增加计算复杂度

内容居中对齐更顺手

让每个格子里的内容(比如图标+文字)居中显示,只需两行:

justify-items: center; /* 水平居中 */
align-items: center;   /* 垂直居中 */

这两个属性作用于整个网格容器,所有子项都会自动居中,无需单独设置每个子项。