如何移除表格单元格上下间距并隐藏标题外的行线?
解决方案
先修正原代码的几个问题
- ID属性在HTML中必须唯一,不能多个元素共用
#Heading/#Data,改用class更合理 <tbody>内不能直接放置<p>标签,这属于无效HTML结构,建议将说明文字放在表格的<caption>中或表格外部
修改后的完整代码
完全匹配你提出的两个需求:行间距紧凑、仅标题行保留横向线条,列线全程完整。
HTML
<table id="Table"> <caption>Item Details</caption> <thead> <tr> <th class="heading">Row</th> <th class="heading">Data</th> <th class="heading">Item</th> <th class="heading">Price</th> </tr> </thead> <tbody> <tr> <td class="data">Row</td> <td class="data">data</td> <td class="data">1</td> <td class="data">100</td> </tr> <tr> <td class="data">Row</td> <td class="data">data</td> <td class="data">2</td> <td class="data">200</td> </tr> </tbody> </table>
CSS
#Table { border-collapse: collapse; border-spacing: 0; } /* 标题单元格:保留完整边框,仅设置左右内边距 */ .heading { border: 1px dashed white; padding: 0 5px; } /* 数据单元格:仅保留左右列线,移除上下边框,上下内边距设为0压缩行间距 */ .data { white-space: nowrap; border-left: 1px dashed white; border-right: 1px dashed white; border-top: none; border-bottom: none; padding: 0 5px; } /* 确保标题行下方的横向线条完整 */ thead tr { border-bottom: 1px dashed white; } caption { margin-bottom: 8px; text-align: left; }
效果说明
- 行间距紧凑:通过将所有单元格的上下内边距设为
0,配合表格的border-collapse: collapse属性,彻底消除行与行之间的额外间距 - 线条控制:
- 列线(左右边框)在所有单元格中保留,保证列线全程完整
- 仅标题行保留横向边框,数据行的上下边框全部移除
内容的提问来源于stack exchange,提问作者Sarahrb
相关产品推荐
相关产品推荐

