如何在 border-collapse 中显示边框?

How to display borders in thead with border-collapse?

我只想折叠外侧边框,而不是内侧边框:

table, tr {
            border: 1px solid black;
            padding: 7px;
            border-collapse: collapse;
}

th {
            background: #ccccff;
        }
<table>
        <thead>
            <tr>
                <th>Data 1</th>
                <th>Data 2</th>
            </tr>
        </thead>
 </table>

不会像 Data 1 | Data 2 那样显示 th 之间的边框,为什么? (以及如何在 th 元素之间添加边框)?

table, tr 中删除 border: 1px solid black。并设置右侧边框border-right: 1px solid black。此外,使用 :last-of-type pseudo-class,删除最后一个元素的边框。

table, tr {
            /*border: 1px solid black;*/
            padding: 7px;
            border-collapse: collapse;
}

th {
            background: #ccccff;
            border-right: 1px solid black;
        }
        
th:last-of-type {
            border-right: unset;
        }
<table>
        <thead>
            <tr>
                <th>Data 1</th>
                <th>Data 2</th>
                <th>Data 3</th>
                <th>Data 4</th>
                <th>Data 5</th>
                <th>Data 6</th>
                <th>Data 7</th>
                <th>Data 8</th>
                <th>Data 9</th>
                <th>Data 10</th>
            </tr>
        </thead>
 </table>

border-collapse并没有你想的效果。它只是防止每个单元格的边界 之间存在间隙。这是没有 border-collapse 时发生的情况:

table {
  border: 1px solid black;
  padding: 7px;
  border-collapse: none;
}

th,td {
  border: 1px solid blue;
}
<table>
  <thead>
    <tr>
      <th>Data 1</th>
      <th>Data 2</th>
    </tr>
  </thead>
</table>

另一个问题是您要将边框添加到 tr - 这只是行,它不适用于行内的单元格。另外仅供参考,在 CSS 中向 table 添加边框只会在整个 table.

的外部添加边框

要将边框应用到单元格,您需要将边框 CSS 添加到 th 元素(并且 td 用于其余 table),例如:

th, td {
  border: 1px solid blue;
}

工作代码段 仅包含带边框的行和带边框的 th/tds 示例:

table,
tr {
  border: 1px solid black;
  padding: 7px;
  border-collapse: collapse;
  text-align:center;
}

th {
  border: 1px solid blue;
}

tr.showborder td {
  border: 1px solid red;
}
<table>
  <thead>
    <tr>
      <th>Data 1</th>
      <th>Data 2</th>
      <th>Data 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>this ROW</td>
      <td> has a</td>
      <td>border</td>
    </tr>
    <tr>
      <td>this ROW</td>
      <td> also has a</td>
      <td>border</td>
    </tr>
    <tr class="showborder">
      <td>The cells in </td>
      <td>this row all</td>
      <td>have borders</td>
    </tr>
    <tr class="showborder">
      <td>The cells in </td>
      <td>this row all</td>
      <td>have borders</td>
    </tr>
  </tbody>
</table>