使用CSS,我想在具有折叠边框的HTML表上添加内部垂直边框。我不希望单元格边框出现在表的外部。从表面上看,这很容易:只需在除一行中第一个单元格外的每个单元格上添加一个左边框。
th:not(:first-child), td:not(:first-child) {
border-left-style: solid;
}
不幸的是,这并没有考虑到跨越两行的列:
<table>
<tbody>
<tr>
<td rowspan="2">foobar</td>
<td>one</td>
</tr>
<tr>
<td>two</td>
</tr>
</tbody>
</table>
在这种情况下,选择器与"0"的单元格不匹配;两个";因为它是行中的第一个<td>
,即使由于上面的rowspan="2"
,它被渲染为在第二列中。
我肯定不是第一个遇到这种情况的人。哪种最新的最佳实践方法可以确保单元格即使参与了包含rowspan
的列也能获得内部垂直边界?
table {
border-collapse: collapse;
}
th:not(:first-child),
td:not(:first-child) {
border-left-style: solid;
}
th[rowspan]:not(:last-child),
td[rowspan]:not(:last-child) {
border-right-style: solid;
}
<table>
<tbody>
<tr>
<td rowspan="2">foobar</td>
<td>one</td>
</tr>
<tr>
<td>two</td>
</tr>
</tbody>
</table>
Andrei Fedorov的答案在大多数情况下都能很好地工作,但在具有行跨度和/或列跨度的表中的表单元格上使用:first-child
/:nth-child
/:last-child
通常充满困难,并且可以定义不起作用的表。例如:
table {
border-collapse: collapse;
}
th:not(:first-child),
td:not(:first-child) {
border-left-style: solid;
}
th[rowspan]:not(:last-child),
td[rowspan]:not(:last-child) {
border-right-style: solid;
}
<table>
<tbody>
<tr>
<td>one</td>
<td rowspan="2">foo<br>bar</td>
</tr>
<tr>
<td rowspan="2">two<br>three</td>
</tr>
<tr>
<td>four</td>
</tr>
</tbody>
</table>
幸运的是,有一种更具体的方法可以满足这一要求,即利用边界冲突解决规则来瓦解边界。该技术是为所有单元格提供两个内联边界,并为表的内联边界提供一种样式";隐藏";。表边界与单元格边界一起折叠,并且在折叠边界规则中;隐藏的";样式值胜过任何其他样式值,因此不会显示外部边界,只保留内部边界。
table {
border-collapse: collapse;
border-inline-style: hidden;
}
td, th {
border-inline-style: solid;
}
<table>
<tbody>
<tr>
<td>one</td>
<td rowspan="2">foo<br>bar</td>
</tr>
<tr>
<td rowspan="2">two<br>three</td>
</tr>
<tr>
<td>four</td>
</tr>
</tbody>
</table>