我有一个非常简单的表格:
<table>
<tr>
<td>col1</td><td>col2</td><td>col3</td>
</tr>
<tr>
<td colspan=2>Mybigcell</td><td>col3</td>
</tr>
</table>
我想要实现的是在第一列周围绘制边框,这意味着在 col1 和 Mybigcell 的左侧部分周围绘制边框。因此,边界必须穿过 Mybigcell 的中间。
可能吗?
最佳答案
您可以使用绝对定位的伪元素来实现此目的。
只需使用下面的 CSS 并添加 class="border"
到某个单元格。它的列将获得边框。
基本上,它的工作原理如下:
- 我们将插入一些绝对定位的伪元素
top: 0
和bottom: 0
。它们的包含 block 将是表格矩形(position: relative
),因此伪元素将增长以覆盖所有列。 - 这些伪元素将插入到单元格的开头 (
::before
)。假设单元格内左对齐,它们将在所需的位置对齐。 - 请注意,它们无法使用
left: 0
进行对齐(并且我们也不能将::after
与right: 0
一起使用)因为包含 block 是表格,而不是单元格。如果包含 block 是单元格,这会更可靠,但边框不会填充所有列。 - 因此,如果某个单元格具有
border
类时,伪元素将被插入到该单元格(左边框)和下一个单元格(右边框)中。 - 但是如果单元格带有
border
class 是该行中的最后一个,它没有右边框,因为没有后续单元格。 - 为了解决这个问题,我使用
:last-child
伪类来检测这种情况,然后插入::after
伪元素left: 100%
。如上所述,它将相对于表格而不是单元格对齐。但假设行中没有丢失单元格,这并不重要,因为单元格的右边缘和表格的右边缘将重合。 - 最后,我使用负边距进行了一些小调整,以使其像素完美。
table {
position: relative; /* Containing block for the borders */
border-collapse: collapse;
}
td {
padding: 1px;
padding-left: 2px; /* Increase by borderWidth */
}
.border:before, .border + :before, .border:last-child:after {
content: ''; /* Enable the pseudo-element */
position: absolute; /* Take it out of flow */
top: 0; /* From the top of the table... */
bottom: 0; /* ...to the bottom of the table */
border-left: 1px solid;/* This produces the border */
margin-left: -2px; /* Same as td's paddingLeft, in negative */
}
.border:last-child:after {
left: 100%; /* Place it at the right */
margin-left: 0; /* Remove the margin set previously */
}
<table> <tr> <td class="border">col1</td> <td>col2</td> <td>col3</td> </tr>
<tr> <td colspan=3>Mybigbigcell</td> </tr> </table><hr />
<table> <tr> <td>col1</td> <td class="border">col2</td> <td>col3</td> </tr>
<tr> <td colspan=3>Mybigbigcell</td> </tr> </table><hr />
<table> <tr> <td>col1</td> <td>col2</td> <td class="border">col3</td> </tr>
<tr> <td colspan=3>Mybigbigcell</td> </tr> </table><hr />
<table> <tr> <td>col1</td> <td>col2</td> <td class="border">col3</td> <td>col4</td> </tr>
<tr> <td colspan=4>Mybigbigbigcell</td> </tr> </table>
如果您想自定义边框或内边距的宽度,请参阅 SCSS:
/* Parameters */
$borderWidth: 1px;
$padding: 1px;
/* Code */
$sum: $borderWidth + $padding;
table {
position: relative;
border-collapse: collapse;
}
td {
padding: $padding;
padding-left: $sum;
}
.border:before, .border + :before, .border:last-child:after {
content: '';
position: absolute;
top: 0;
bottom: 0;
border-left: $borderWidth solid;
margin-left: - $sum;
}
.border:last-child:after {
left: 100%;
margin-left: 0;
}
关于html/css : Draw borders through a table cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32361556/