如何为 3x3 table 使用 CSS 边框图像,使得每 2 个单元格之间只有 1 个边框?

How to use CSS border image for a 3x3 table such that there is only 1 border between every 2 cells?

我一直在试验 border-image 属性 并试图制作一个 3x3 的网格,在外面有一个边框,每个单元格之间都有一个边框。问题是如果我像这样在 table 单元格上使用边框图像 属性:

td {
    border: 10px solid black;
    border-image-source: url(https://mdn.mozillademos.org/files/6009/border-image-2.png);
    border-image-slice: 33% 33% 33% 33%;
    border-image-repeat: round round;
    border-image-outset: 0px 0px 0px 0px;
}

最终每个单元格之间有两条边界。如果我的意思不太清楚,请参阅 http://codepen.io/katieyang/pen/RpKpNW?editors=0100

我该如何解决这个问题?

提前致谢!

您 运行 陷入了 table 风格的众多怪癖之一。对于普通边框,您可以通过使用 border-collapse: collapse 来解决这个问题,但这似乎在 table 单元格上击败了 border-image,至少在某些浏览器中是这样。*

如果我是你,我会通过设置 ::after 伪元素的样式而不是 <td> 元素本身来解决这个问题。

您可以在下面的代码片段中看到它的工作原理,但这里是重要的部分:

  1. border-collapse: collapse;<table>
  2. <td>s 和 position: relative; 上所需宽度的透明边框,因此伪元素可以绝对定位在
  3. 每个 <td> 上带有 position: absolute;::after 伪元素,其位置覆盖 <td> 及其边界
  4. 每个伪元素的顶部和左侧 border-image,每行最后一个伪元素的右侧 border-image,伪元素的底部 border-image底行的。

在代码片段中,我添加了一些 :hover 样式来显示伪元素及其边框的位置。

table {
  border-collapse: collapse;
  width: 200px;
  height: 200px;
  background-color: #ccc;
  text-align: center;
  color: white;
}

td {
  position: relative;
  border: 10px solid transparent;
}

td::after {
  content: '';
  position: absolute;
  top: -10px;
  left: -10px;
  width: 100%;
  height: 100%;
  
  border: 10px solid blue;
  border-image-source: url(//mdn.mozillademos.org/files/6009/border-image-2.png);
  border-image-slice: 33%;
  border-image-repeat: round;
  border-image-outset: 0;
}

td:hover::after {
  /* for demonstration only */
  border-image: none;
  background-color: rgba(0,0,255,0.33);
}

td:not(:last-child)::after {
  border-right: 0;
}

tr:not(:last-child) td::after {
  border-bottom: 0;
}
<table class="box">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
    <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
    <tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
  </tr>
</table>

*当前的border-image spec表示:

The ‘border-image’ properties apply to the border of tables and inline tables that have ‘border-collapse’ set to ‘collapse’. However, this specification does not define how such an image border is rendered. In particular, it does not define how the image border interacts with the borders of cells, rows and row groups at the edges of the table.

...但是 MDN 表示它适用于 "all elements, except internal table elements when border-collapse is collapse,",这似乎是 Chrome 和 Firefox 中的当前行为,至少。