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

如何为井字棋CSS Grid布局添加仅内部边框?

解决CSS Grid井字棋仅显示内部边框的问题

看起来你已经搭好了井字棋的Grid布局框架,现在要解决的是只在网格内部添加边框、避免外部出现多余边框的问题对吧?我给你两种实用的解决方案,你可以根据需求选择:

方法1:利用Grid Gap + 容器背景色(最简洁)

这个方法不需要给子元素加任何边框样式,靠Grid的间隙和容器背景色模拟内部边框,代码量最少,也不会有边框重叠的问题:

:root { 
  --border: 2px dashed #393939; 
  --symbol-color: #FF7F5B;
  --cell-bg: #fff; /* 单元格背景色,和页面背景一致即可 */
} 

.grid { 
  height: 100%; 
  display: grid; 
  grid-template-columns: repeat(3, 1fr); /* 用1fr比calc(100%/3)更简洁适配 */
  grid-template-rows: repeat(3, 1fr);
  gap: var(--border); /* 间隙大小等于边框宽度 */
  background-color: var(--border); /* 容器背景色设为边框颜色 */
} 

.child { 
  display: flex; 
  align-items: center;
  justify-content: center; /* 替换align-content,实现内容水平居中 */
  background-color: var(--cell-bg); /* 单元格背景盖住容器背景,仅露出间隙部分 */
  color: var(--symbol-color); 
  font-size: 2.5rem; 
}

原理很直观:Grid的gap会在单元格之间留出空隙,容器的背景色透过空隙显示,刚好形成内部分隔边框;而单元格的背景色会覆盖容器背景,所以外部不会出现边框。

方法2:给子元素选择性添加边框

如果你更倾向于直接给子元素加边框,可以通过:nth-child选择器精准控制,只给需要的边加边框,避免外部出现边框:

:root { 
  --border: 2px dashed #393939; 
  --symbol-color: #FF7F5B;
} 

.grid { 
  height: 100%; 
  display: grid; 
  grid-template-columns: repeat(3, 1fr); 
  grid-template-rows: repeat(3, 1fr);
} 

.child { 
  display: flex; 
  align-items: center;
  justify-content: center;
  color: var(--symbol-color); 
  font-size: 2.5rem; 
}

/* 给第1、2、4、5、7、8个单元格加右边框(排除第三列的单元格) */
.child:nth-child(1),
.child:nth-child(2),
.child:nth-child(4),
.child:nth-child(5),
.child:nth-child(7),
.child:nth-child(8) {
  border-right: var(--border);
}

/* 给第1、2、3、4、5、6个单元格加下边框(排除第三行的单元格) */
.child:nth-child(1),
.child:nth-child(2),
.child:nth-child(3),
.child:nth-child(4),
.child:nth-child(5),
.child:nth-child(6) {
  border-bottom: var(--border);
}

这种方法的好处是可以给边框单独设置差异化样式(比如不同颜色、线型),但需要逐个选择子元素,代码量会稍多一些。

两种方法都能实现你要的“仅网格内部有边框”的效果,推荐第一种,更简洁易维护~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:50:58