html - 如何仅在表格内应用边框?

我想弄清楚如何只在表格内添加边框。当我这样做时:

table {
    border: 0;
}
table td, table th {
    border: 1px solid black;
}

边框围绕整个表格以及表格单元格之间。我想要实现的是仅在表格单元格周围的表格内有边框(表格周围没有外边框)。

这是我用于表格的标记(尽管我认为这并不重要):

<table>
    <tr>
        <th>Heading 1</th>
        <th>Heading 2</th>
    </tr>
    <tr>
        <td>Cell (1,1)</td>
        <td>Cell (1,2)</td>
    </tr>
    <tr>
        <td>Cell (2,1)</td>
        <td>Cell (2,2)</td>
    </tr>
    <tr>
        <td>Cell (3,1)</td>
        <td>Cell (3,2)</td>
    </tr>
</table>

以下是我应用于大多数表格的一些基本样式:

table {
    border-collapse: collapse;
    border-spacing: 0;
}

最佳答案

如果您正在做我认为您正在尝试做的事情,您将需要更多这样的东西:

table {
  border-collapse: collapse;
}
table td, table th {
  border: 1px solid black;
}
table tr:first-child th {
  border-top: 0;
}
table tr:last-child td {
  border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

jsFiddle Demo

问题是您在所有单元格周围设置了一个“完整边框”,这使得它看起来好像整个表格都有一个边框。

干杯。

编辑:关于这些伪类的更多信息可以在 quirksmode 上找到。 ,而且,不出所料,你几乎是 S.O.L.在 IE 支持方面。

https://stackoverflow.com/questions/1257430/

相关文章:

image - 如何在保持图像纵横比的同时拉伸(stretch)图像以填充

html - 表格固定标题和可滚动正文

html - 如何在 div 中使按钮居中?

html - 为什么类型为 "number"的 html 输入允许在字段中输入字母 'e'?

html - 将居中文本添加到水平线的中间

html - 如何让 HTML 5 输入类型 ="date"在 Firefox 和/或 IE 10

java - 如何使用 Java 有效地解析 HTML?

html - 有必要写 HEAD、BODY 和 HTML 标签吗?

html - 如何更改 Canvas 元素中元素的不透明度(alpha、透明度)?

javascript - 获取元素的父div