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

使用CSS实现带间距棋盘格:方块间距与内部方块实现求助

解决棋盘格布局的间距与方块样式问题

先修正HTML结构错误

你当前的HTML里,<table>标签内直接嵌套<div>不符合规范,<tr>必须直接放在<table>或<tbody>中,多余的<div>会导致布局异常。修正后的完整HTML示例:

<table>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
  <tr>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
    <th><span></span></th>
  </tr>
</table>

调整CSS实现间距与棋盘格样式

  1. 方块间距:给<table>设置border-collapse: separate和border-spacing控制单元格空隙,替代原来的padding(padding是单元格内部空间)。
  2. 内部方块效果:通过<th>嵌套的<span>实现内外两层颜色,再利用行和列的奇偶选择器实现棋盘格交替效果。

完整CSS代码:

table {
  border-collapse: separate;
  border-spacing: 10px; /* 控制方块之间的间距 */
}

th {
  width: 50px;
  height: 50px;
  padding: 0;
  background: transparent; /* 清空默认背景,让外层间距显示 */
}

th span {
  display: block;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

/* 奇数行样式:奇列绿边框红内部,偶列红边框绿内部 */
tr:nth-child(odd) th:nth-child(odd) span {
  border: 5px solid rgb(89, 218, 89);
  background: orangered;
}

tr:nth-child(odd) th:nth-child(even) span {
  border: 5px solid orangered;
  background: rgb(89, 218, 89);
}

/* 偶数行反转样式:奇列红边框绿内部,偶列绿边框红内部 */
tr:nth-child(even) th:nth-child(odd) span {
  border: 5px solid orangered;
  background: rgb(89, 218, 89);
}

tr:nth-child(even) th:nth-child(even) span {
  border: 5px solid rgb(89, 218, 89);
  background: orangered;
}

关键说明

  • 移除HTML中无效的<div>标签,保证表格结构符合规范;
  • 用border-spacing实现方块间的间距,这是表格布局控制单元格空隙的正确方式;
  • 通过嵌套<span>实现每个方块的内外两层颜色,结合行和列的奇偶选择器,实现完整的棋盘格交替效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:01:07