
本文介绍使用 CSS Grid、aspect-ratio 和 vw 字体单位,解决井字棋(Tic Tac Toe)中“X/O”符号在不同屏幕尺寸下失衡、偏移或溢出的问题,确保文字始终精准居中且随容器等比缩放。
本文介绍使用 css grid、`aspect-ratio` 和 `vw` 字体单位,解决井字棋(tic tac toe)中“x/o”符号在不同屏幕尺寸下失衡、偏移或溢出的问题,确保文字始终精准居中且随容器等比缩放。
构建一个真正响应式的井字棋界面,关键在于让每个格子保持正方形比例,并使文本大小与视口宽度动态关联,而非依赖固定像素值。原方案使用 flex + padding-bottom 实现正方形技巧虽有效,但存在维护复杂、语义不清、响应断点脆弱等缺陷;而现代 CSS 提供了更简洁、健壮的替代方案。
✅ 推荐方案:Grid + aspect-ratio + place-items + vw
首先,将棋盘容器改用 CSS Grid 布局,明确声明 3×3 网格结构:
#cellContainer {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2px; /* 替代 outline,更可控 */
max-width: 300px;
margin: 1.5rem auto;
border: 4px solid #000;
}其次,为每个 .cell 设置固有宽高比,并启用网格居中能力:
.cell {
aspect-ratio: 1; /* 强制正方形,无需 padding-bottom 技巧 */
box-sizing: border-box;
border: 2px solid #000;
cursor: pointer;
display: grid;
place-items: center; /* 水平+垂直完美居中(含文本、图标等任意内容) */
font-size: 10vw; /* 字体随视口宽度线性缩放,10vw ≈ 屏幕宽度的10% */
line-height: 1; /* 避免行高干扰居中 */
font-family: "Permanent Marker", cursive;
}? 为什么 10vw 合适?
在典型移动端(如 375px 宽屏幕),10vw = 37.5px,足够清晰显示;在桌面端(1440px),10vw = 144px,仍能被 max-width: 300px 的容器约束——此时可通过 clamp() 进一步优化上限:
font-size: clamp(24px, 10vw, 64px); /* 最小24px,最大64px,中间弹性缩放 */
⚠️ 注意事项与兼容性提醒
- aspect-ratio 已获主流浏览器(Chrome 88+, Firefox 89+, Safari 15.4+)全面支持;若需兼容旧版 Safari(<15.4),可回退至 padding-bottom 方案,但建议优先使用现代语法并搭配 CanIUse 检查目标用户环境。
- place-items: center 是 justify-items: center + align-items: center 的简写,仅对 Grid/Flex 容器生效——务必确保 .cell 的 display: grid(或 flex)已启用。
- 避免在 .cell 中混用 text-align: center 和 line-height 居中,易与 place-items 冲突;统一交由 display: grid 处理最可靠。
- 若后续需添加 SVG 图标或动画效果,place-items 同样适用,无需额外调整布局逻辑。
✅ 最终 HTML 结构(精简优化版)
<div id="gameContainer">
<h1>Tic Tac Toe</h1>
<div id="cellContainer">
<div cellIndex="0" class="cell">X</div>
<div cellIndex="1" class="cell">O</div>
<div cellIndex="2" class="cell"></div>
<div cellIndex="3" class="cell"></div>
<div cellIndex="4" class="cell"></div>
<div cellIndex="5" class="cell"></div>
<div cellIndex="6" class="cell"></div>
<div cellIndex="7" class="cell"></div>
<div cellIndex="8" class="cell"></div>
</div>
<h2 id="statusText">Player X's turn</h2>
<button id="restartBtn">Restart Game</button>
</div>该方案摒弃了脆弱的 flex 宽度计算与手动 font-size 调整,转而利用浏览器原生布局能力,实现「一次编写、全端适配」。无论手机横屏、平板竖屏,还是超宽显示器,X/O 始终稳居格子中央,大小恰到好处——这才是现代响应式 UI 的正确打开方式。

















