使用rowspan且列数不均时,如何消除表格中的空白区域?
嘿,我来帮你搞定这个rowspan导致的空白问题!
你碰到的空白其实是因为首行只有3个<td>,但表格总共有5列,后面两列的单元格位置在首行是空着的,当rowspan里的文本换行后,这个空白区域就变得格外显眼。之前用display:none的td没效果,是因为display:none会让单元格完全不占据空间,表格还是会预留出那两列的位置,所以空白依然存在。
这里有个简单又有效的解决办法:给首行补上对应列的空<td>,然后把这些空单元格的边框和背景设为透明/无,这样它们会占据对应的位置,但视觉上完全看不到,自然就消除空白了。
修改后的代码如下:
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/> <table class="table table-bordered" style="table-layout: fixed;"> <colgroup> <col span="1" style="width: 20%;"> <col span="1" style="width: 40%;"> <col span="1" style="width: 20%; white-space: normal;"> <col span="1" style="width: 20%;"> <col span="1" style="width: 20%;"> </colgroup> <tr> <th>Year</th> <th>Month</th> <th>Savings</th> <th>Savings for holiday!</th> <th>Random Words</th> </tr> <tr id='haha'> <td rowspan="3">2020</td> <td rowspan="3">January</td> <td rowspan="3">text in here should be long enough to take more than 1 row</td> <!-- 添加这两个空td,消除空白 --> <td style="border: none; background: transparent;"></td> <td style="border: none; background: transparent;"></td> </tr> <tr> <td>$100</td> <td>Hello</td> </tr> <tr> <td>$200</td> <td>There</td> </tr> </table>
要是你不想写内联样式,也可以给这些空td加个类,比如.empty-cell,然后在CSS里统一定义:
.empty-cell { border: none !important; background-color: transparent !important; }
这样代码更整洁,复用性也更强。
内容的提问来源于stack exchange,提问作者Smudge the Cat
相关产品推荐
相关产品推荐

